2016-09-01 60 views
4

我想在关闭子进程后继续执行命令。我有以下代码,但不执行fsutil。我该怎么做?关闭python命令子进程

import os 
from subprocess import Popen, PIPE, STDOUT 

os.system('mkdir c:\\temp\\vhd') 
p = Popen(["diskpart"], stdin=PIPE, stdout=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") 
p.stdout.close 
os.system('fsutil file createnew r:\dummy.txt 6553600') #this doesn´t get executed 
+0

请不要再使用'os.system()'。这是非常老式的,建议不推荐使用很长时间。 –

+0

你如何不建议在我的代码中包含fsutil行? –

+0

不应该是'p.stdout.close()'?我想你错过了一些括号。 –

回答

1

至少,我认为你需要改变你的代码看起来像这样:

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()

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

你可以替换p.communicate()p.wait(),但这个警告在documentation for Popen.wait()

警告这种使用标准输出=管和/或标准错误= PIPE和子进程产生时就会死锁足够的输出到管道,以至于阻止等待OS管道缓冲区接受更多数据。使用通信()来避免这种情况。

+0

现在感谢看起来不错。 –