关闭python命令子进程

关闭python命令子进程,python,subprocess,stdout,Python,Subprocess,Stdout,我想在关闭子流程后继续使用命令。我有以下代码,但未执行fsutil。我怎么做 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 typ

我想在关闭子流程后继续使用命令。我有以下代码,但未执行
fsutil
。我怎么做

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

至少,我认为您需要更改代码,使其看起来像这样:

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')
从:

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

您可以将
p.communicate()
替换为
p.wait()
,但是在

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


请不要再使用
os.system()
。这是一个非常过时的建议,已被弃用很长时间。如果不在我的代码中包含fsutil行,您有何建议?它不应该是
p.stdout.close()
?我认为您缺少了一些括号。实际上,在
p.stdin.write(“exit\n”)
之后是否缺少了一个
p.communicate()
?添加了()后,得到了相同的结果。p、 通信()?那会怎么样?