[英]p.stdout.read() doesn't work in my Python 3 codes
我尝试使用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"
,那么您的示例将根据需要为我工作,但如果我只是说"app"
则不行。 据推测这是因为,在类似unix的系统上(与Windows不同),默认情况下当前工作目录不在shell路径上,因此根本找不到"app"
。
如果你说过
print(p.stderr.read())
然后它可以告诉你问题本身是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.