簡體   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