python subprocess.stdout.readline 没有

标签 python linux

我有一段 python 代码,它通过 subprocess 模块调用二进制文件。此二进制文件从 stdin 读取数据并将其他数据输出到 stdout,然后由 python 代码收集这些数据。

下面是我如何在 shell 中使用这个二进制文件:

$ ./check # start reading from stdin here
param_card_orig.dat
0.123809
42.821 0 0 42.821 
91.2246 0 0 -91.2246 
14.5521 -12.9194 -0.441262 6.68258 
33.8782 -4.04952 5.37574 -33.2029 
35.3909 22.0683 2.04142 27.5923 
50.2244 -5.09935 -6.9759 -49.4755 

在每一行(包括最后一行)之后有一个返回,我从中得到输出

1.53852538054399053E-004

再次以换行符结束。但是,尝试将其放入这样的 python 代码中:

import subprocess

p = subprocess.Popen("./check", stdout=subprocess.PIPE, stdin=subprocess.PIPE)
p.stdin.write("param_card_orig.dat\n")
p.stdin.write("0.123809\n")
p.stdin.write("42.821 0 0 42.821 \n")
p.stdin.write("91.2246 0 0 -91.2246 \n")
p.stdin.write("14.5521 -12.9194 -0.441262 6.68258 \n")
p.stdin.write("33.8782 -4.04952 5.37574 -33.2029 \n")
p.stdin.write("35.3909 22.0683 2.04142 27.5923 \n")
p.stdin.write("50.2244 -5.09935 -6.9759 -49.4755 \n")

print("now waiting for input")

print(p.stdout.readline())

我收到的正是这个:

now waiting for input

程序挂起,显然是在等待某种通信的发生。这部分是有意的 - check 二进制文件应该保持事件状态并等待进一步的输入,一旦提供了进一步的完整输入就返回计算的输出 - 但由于第一个输入已完成,我应该收到计算结果,但我显然没有收到,否则我们会看到打印输出。当我使用 CTRL+C 手动中断执行时,它告诉我

^CTraceback (most recent call last):
File "testpipe.py", line 15, in <module>
print(p.stdout.readline())

这是怎么回事?这是我处理管道的方式有问题吗?这是缺少 EOF 或缺少换行符的问题吗?

PS:我发现了这个问题Python subprocess.stdout.readline() hang ,这可能是相同的,但没有收到答案。

PPS:以防万一,python 版本是 Python 2.6.6。

最佳答案

您是否尝试过使用 p.stdout.read() 而不是 readline()?它适用于以下测试代码,其中 invoker.py 使用 invoked.py 创建管道。

调用.py

#!/usr/bin/python
import sys

# Print a Hello notice
sys.stdout.write("I have been invoked!\n")

# Read the value coming from the pipe
value = sys.stdin.readline()

# Return a "processed" value
sys.stdout.write("New: " + value)

invoker.py

import subprocess

# Start pipe with other file
p = subprocess.Popen("./invoked.py", stdout=subprocess.PIPE, stdin=subprocess.PIPE)

# Send a value to the other file
p.stdin.write("Value!\n")

# Print the result coming from the other file
print(p.stdout.read())

关于python subprocess.stdout.readline 没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32812157/

相关文章:

可以突出显示所选单词的所有实例的 Linux 编辑器

Python:读取png图像的默认/常用方法

python - Pyside2 将键绑定(bind)到方法调用而不是按钮或菜单

linux - 电子邮件中的所有行一起运行

c++ - 启动浏览器的 Posixy 方式?

linux - 什么是 Linux test -a 命令测试?

java - WrapperBeanGenerator 错误 : Not creating ASM Type for type

python - 关于如何创建 Pandas DataFrame 的困惑

python - 如何使用 ChromeOptions 在 Python selenium 中禁用 CSS

python - 从 Windows 迁移到 Linux