python - subprocess.Popen 与 CLI 提示符交互

标签 python bash subprocess command-line-interface popen

我正在尝试使用 subprocess.Popen 写入和读取 CLI 程序。

因此,每次您向 CLI 发出命令时,它都会打印一些内容,而这些内容就是我想要阅读的内容。我将尝试用一个具体的例子来解释我想要做什么,以便每个人都可以尝试。

因此,我将使用存在问题的 ipython,而不是使用我的真实程序:

p = subprocess.Popen(['ipython'],stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate(input="5+5")

如果您使用Popen.communicate(input=command),您将在stdout处获得ipython将在终端中打印的所有文本如果我直接从 shell 执行它。

我想做的事情:

而不是使用沟通。我希望能够发送单独的命令并读取立即输出。例如我想做:

p.stdin.write("5+5")
out1 = p.stdout.read()

p.stdin.write("5*10")
out2 = p.stdout.read()

因此 out1 应为 5,out2 应为 50。

问题:

在关闭 stdin 之前,您无法读取 stdout

你是怎么做到的?我无法使用 read(n)readline() 因为在我的实际应用程序中我不知道输出的长度。

最佳答案

经过一些小的修改,我能够从 this question 开始使用该方法。工作。

使用Python3:

>>> from subprocess import Popen, PIPE
>>> 
>>> fw = open("tmpout", "wb")
>>> fr = open("tmpout", "r")
>>> p = Popen("ipython", stdin=PIPE, stdout=fw, stderr=fw, bufsize=1, universal_newlines=True)
>>> header = fr.read()
>>> p.stdin.write("100*50\n")
7
>>> fr.read()
'\nIn [1]: Out[1]: \n5000\n'
>>> p.stdin.write("2/3.\n")
5
>>> fr.read()
'\nIn [2]: Out[2]: \n0.6667\n'

如您所见,它是交互式工作的。

一个技巧是,在 Py3 下,bufsize=1 仅在 universal_newlines=True 时才使 I/O 行缓冲.

关于python - subprocess.Popen 与 CLI 提示符交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47948512/

相关文章:

python - numpy.nditer() 的使用

反向的 Python 日期时间

bash cat 多个文件内容到没有换行符的单个字符串

python - 更清洁的方式来填充数据框?

Python urllib3 urlopen 不使用特定错误的重试

linux - 在多个目录中创建多个文件

bash - 将 bash 变量传递给内联 perl 脚本

python - WindowsError [错误 5] 访问被拒绝

ping 命令的 Python 包装器在收到 pong 时停止

Linux下Python子进程Popen准备Python路径