简体   繁体   English

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

[英]How to communicate with command line program using python?

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)

how do i pass and communicate with the cmd using python. 我如何使用python通过cmd并与之通信。

Thanks. 谢谢。 (using windows platform) (使用Windows平台)

The docs on communicate() explain this: communicate()文档对此进行了解释:

Interact with process: Send data to stdin. 与进程交互:将数据发送到stdin。 Read data from stdout and stderr, until end-of-file is reached. 从stdout和stderr读取数据,直到到达文件末尾。 Wait for process to terminate. 等待进程终止。

communicate() blocks once the input has been sent until the program finishes executing. 一旦发送了输入, communicate()阻塞,直到程序执行完毕。 In your example, the program waits for more input after you send "1" , but Python waits for it to exit before it gets to the next line, meaning the whole thing deadlocks. 在您的示例中,程序在发送"1"之后等待更多的输入,但是Python在它到达下一行之前等待它退出,这意味着整个过程都陷入了僵局。

If you want to read and write a lot interchangeably, make pipes to stdin / stdout and write/read to/from them. 如果您想互换地进行大量读写,请使用管道连接stdin / stdout并对其进行读写操作。

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

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