【问题标题】:closing python command subprocesses关闭 python 命令子进程
【发布时间】:2017-01-09 20:21:20
【问题描述】:

我想在关闭子进程后继续执行命令。我有以下代码,但 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

【问题讨论】:

  • 请不要再使用os.system()。它非常老式,建议弃用很长时间。
  • 如果不在我的代码中包含 fsutil 行,您如何建议?
  • 不应该是p.stdout.close()吗?我认为您缺少一些括号。
  • 其实你不是在p.stdin.write("exit\n")后面少了一个p.communicate()吗?
  • 加上 () 得到了相同的结果。 p.communicate()?那会怎么样?

标签: python subprocess stdout


【解决方案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() 中有此警告

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

【讨论】:

    猜你喜欢
    • 2015-08-20
    • 2013-07-19
    • 1970-01-01
    • 2020-11-26
    • 2012-10-31
    • 1970-01-01
    • 2011-12-30
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多