Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
p、 stdout.read()不';在我的Python 3代码中不起作用_Python_Subprocess_Stdout - Fatal编程技术网

p、 stdout.read()不';在我的Python 3代码中不起作用

p、 stdout.read()不';在我的Python 3代码中不起作用,python,subprocess,stdout,Python,Subprocess,Stdout,我尝试使用MAC OS中的subprocess模块创建一个子进程。下面是我的代码: 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

我尝试使用MAC OS中的subprocess模块创建一个子进程。下面是我的代码:

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;
}
为什么输出是那个奇怪的字符串?

输出
b'
表示“一个空字节字符串”

这是因为没有要传递的
stdout
输出,因为您的子流程尚未成功启动

如果我以
“/app”
的形式打开子流程,那么您的示例对我来说是可行的,但如果我只是说
“app”
,则不可行。这大概是因为,在类unix系统(与Windows不同)上,默认情况下当前工作目录不在shell路径上,因此根本找不到
“app”

如果你说

print(p.stderr.read())

然后它就可以告诉你问题本身了。

我假设
应用程序在从命令行独立运行时能像预期的那样工作?是的,我仔细检查了。只是一个小提示:你可以简单地编写
b“3\n”而不是
字节(“3\n”,“ascii”)
@injoy:这是因为子流程流处理字节字符串而不是Unicode字符串。有关差异的一些介绍性信息,请参见。使用
p=Popen(“./app”,stdin=PIPE,stdout=PIPE);输出=p.communicate(b“3\n4”)[0];打印(p.returncode)
。如果同时设置了
stdout
stderr
;您需要同时读取这两条流。
print(p.stderr.read())