【问题标题】:How to communicate with command line program using python?如何使用python与命令行程序进行通信?
【发布时间】:2012-10-05 08:52:08
【问题描述】:
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平台)

【问题讨论】:

  • 为什么不把receiver进程的相关部分也贴在这里?
  • 可以试试proc.stdin.write(data_to_write)

标签: python windows cmd subprocess communicate


【解决方案1】:

docs on communicate() 解释一下:

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

communicate() 在发送输入后阻塞,直到程序完成执行。在您的示例中,程序在您发送 "1" 后等待更多输入,但 Python 会等待它退出,然后再进入下一行,这意味着整个事情都死锁了。

如果你想交替读写,make pipesstdin/stdout 并写入/读取它们。

【讨论】:

  • 感谢它帮助我了解下一步该做什么。
  • @user1717522 -- 如果您的问题得到了满意的答案,您应该将其标记为已接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
  • 2020-10-01
  • 2014-01-21
相关资源
最近更新 更多