如何使用python与命令行程序进行通信?

问题描述 投票:0回答:1
import subprocess
import sys

proc = subprocess.Popen(["program.exe"], stdin=subprocess.PIPE) #the cmd program opens
proc.communicate(input="filename.txt") #here the filename should be entered (runs)
#then the program asks to enter a number:
proc.communicate(input="1") #(the cmd stops here and nothing is passed)
proc.communicate(input="2") # (same not passing anything)

如何使用 python 传递并与 cmd 进行通信。

(使用windows平台)

python windows cmd subprocess
1个回答
6
投票

communicate()

 上的 文档对此进行了解释:

与进程交互:将数据发送到标准输入。从标准输出读取数据并 stderr,直到到达文件末尾。等待进程终止。

一旦输入被发送,

communicate()
就会阻塞,直到程序完成执行。在您的示例中,程序在您发送
"1"
后等待更多输入,但 Python 会在到达下一行之前等待它退出,这意味着整个过程陷入僵局。

如果您想互换地进行大量读写,请制作管道

stdin
/
stdout
并对其进行写入/读取。

© www.soinside.com 2019 - 2024. All rights reserved.