Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.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
Python P.communicate()不返回输出,但退出代码为0_Python - Fatal编程技术网

Python P.communicate()不返回输出,但退出代码为0

Python P.communicate()不返回输出,但退出代码为0,python,Python,下面的代码没有输出,但也没有产生错误。当在命令行上手动键入命令时,我会得到很多输出 grepCommand = "box | grep " + grepHostKey grepCommand = grepCommand.split() p = subprocess.Popen(grepCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (hostString, err) = p.communicate() print hostStr

下面的代码没有输出,但也没有产生错误。当在命令行上手动键入命令时,我会得到很多输出

grepCommand = "box | grep " + grepHostKey
grepCommand = grepCommand.split()

p = subprocess.Popen(grepCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(hostString, err) = p.communicate()
print hostString    
print err
输出:


如果我添加shell=True,我只会从“box”命令获得预期的响应,它不会通过管道传输到grep中。我已经看到建议不要使用shell=True。我试过bufsize=8192,它足够大,可以处理,但仍然没有。你有什么想法吗

管道是一个外壳符号。这就是为什么它只能在shell=True时工作。但正如你所说,这不是最佳做法。下面是一段代码,您可以使用它将命令与子流程手动关联

box_process = Popen(["box"], stdout=PIPE)
grep_process = Popen(["grep", grepHostKey], stdin=box_process.stdout, stdout=PIPE)
box_process.stdout.close()
(hostString, err) = grep_process.communicate()
不推荐的向上投票
shell=True
:)