繁体   English   中英

python子进程在交互模式下工作,但不在脚本中工作

[英]python subprocess is working in interactive mode but in not script

在Windows中,我必须执行如下命令:

process = subprocess.Popen([r'C:\Program Files (x86)\xxx\xxx.exe', '-n', '@iseasn2a7.sd.xxxx.com:3944#dc', '-d', r'D:\test\file.txt'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
process.communicate()

这在python交互模式下可以正常工作,但根本无法从python脚本执行。

可能是什么问题?

Popen.communicate本身不打印任何内容,但会返回stdout和stderr输出。 除此之外,因为指定stdout=PIPE, stderr=...的代码stdout=PIPE, stderr=...创建Popen ,它捕获输出(不让子流程将输出直接输出到父流程的stdout)。

您需要手动打印返回值:

process = ....
output, error = process.communicate()
print output

如果您不希望这样做,请不要通过忽略stdout=PIPE, stderr=...捕获stdout输出。

然后,您不需要使用communicate ,只需wait

process = subprocess.Popen([...], shell=True)
process.wait()

或者,您可以使用subprocess.call来执行子流程并等待其终止:

subprocess.call([...], shell=True)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM