问题
I try to create a sub-process using the subprocess module in MAC OS. Below is my code:
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())
The source code of app is :
#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;
}
When I execute the python code, the output is :
b''
Why the output is that weird string?
回答1:
The output b''
means "an empty byte string".
This is because there is no stdout
output to deliver, because your subprocess has not launched successfully.
Your example works for me as desired if I open the subprocess as "./app"
but not if I just say "app"
. Presumably this is because, on unix-like systems (unlike Windows), the current working directory is not on the shell path by default, so "app"
is simply not found.
If you had said
print(p.stderr.read())
then it could have told you what the problem was itself.
来源:https://stackoverflow.com/questions/20724549/p-stdout-read-doesnt-work-in-my-python-3-codes