我尝试使用 MAC OS 中的子进程模块创建子进程。下面是我的代码:
import subprocess
p = subprocess.Popen("app",
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True)
p.stdin.write(bytes("3\n", "ascii"))
p.stdin.write(bytes("4\n", "ascii"))
print(p.stdout.read())
应用程序的源代码是:
#include <iostream>
using namespace std;
int main()
{
int x, y;
cout << "input x: " << endl;
cin >> x;
cout << "input y: " << endl;
cin >> y;
cout << x << " + " << y << " = " << x + y << endl;
return 0;
}
当我执行Python代码时,输出是:
b''
为什么输出是那个奇怪的字符串?
最佳答案
输出b''
表示“空字节字符串”。
这是因为没有 stdout
输出可传递,因为您的子进程尚未成功启动。
如果我将子进程打开为 "./app"
但如果我只是说 "app"
,则您的示例对我有用。大概这是因为,在类 UNIX 系统上(与 Windows 不同),默认情况下当前工作目录不在 shell 路径上,因此根本找不到 "app"
。
如果你说过
print(p.stderr.read())
那么它本身就可以告诉您问题是什么。
关于python - p.stdout.read() 在我的 Python 3 代码中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20724549/