p.stdout.read() doesn't work in my Python 3 codes

隐身守侯 提交于 2020-01-24 21:48:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!