关闭python命令子进程

时间:2016-09-01 20:12:51

标签: python subprocess stdout

我想在关闭子进程后继续执行命令。我有以下代码但B未执行。我怎么能这样做?

B

1 个答案:

答案 0 :(得分:2)

至少,我认为您需要将代码更改为:

import os
from subprocess import Popen, PIPE

os.system('mkdir c:\\temp\\vhd')
p = Popen(["diskpart"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.stdin.write("create vdisk file=c:\\temp\\vhd\\test.vhd maximum=2000 type=expandable\n")
p.stdin.write("attach vdisk\n")
p.stdin.write("create partition primary size=10\n")
p.stdin.write("format fs=ntfs quick\n")
p.stdin.write("assign letter=r\n")
p.stdin.write("exit\n")
results, errors = p.communicate()
os.system('fsutil file createnew r:\dummy.txt 6553600')

来自documentation for Popen.communicate()

  

与流程交互:将数据发送到stdin。从stdout和stderr读取数据,直到达到文件结尾。等待进程终止。可选的输入参数应该是要发送到子进程的字符串,如果没有数据应该发送给子进程,则为None。

您可以将p.communicate()替换为p.wait(),但documentation for Popen.wait()

中有此警告
  

警告当使用stdout = PIPE和/或stderr = PIPE时,这将导致死锁,并且子进程会为管道生成足够的输出,以阻止等待OS管道缓冲区接受更多数据。使用communic()来避免这种情况。

相关问题