Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.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 为什么要在subprocess.Popen中使用stdout=PIPE?_Python_Process_Command_Pipe - Fatal编程技术网

Python 为什么要在subprocess.Popen中使用stdout=PIPE?

Python 为什么要在subprocess.Popen中使用stdout=PIPE?,python,process,command,pipe,Python,Process,Command,Pipe,在上面的Popen调用中,如果我删除stdout=PIPE,我将在输出中的ls-l的每个列表之后获得换行符。但如果使用stdout=PIPE,则会显示\n,而不是换行符,如下所示 from subprocess import PIPE,Popen p = Popen("ls -l",shell=True,stderr=PIPE,stdout=PIPE) (out,err) = p.communicate() print(out, err) 在子流程.Popen的情况下,管道究竟是如何工作的?

在上面的Popen调用中,如果我删除
stdout=PIPE
,我将在输出中的
ls-l
的每个列表之后获得换行符。但如果使用
stdout=PIPE
,则会显示
\n
,而不是换行符,如下所示

from subprocess import PIPE,Popen

p = Popen("ls -l",shell=True,stderr=PIPE,stdout=PIPE)
(out,err) = p.communicate()
print(out, err)
子流程.Popen
的情况下,
管道
究竟是如何工作的?我们为什么需要它?我没有使用它也得到了正确的输出?我们是否使用它来获取两个stderr、stdout?

删除
print()
调用以查看差异

当您没有将
ls
输出通过管道传输到Python时,它将直接显示在您的终端上;它的输出到终端。如果通过管道将其传输到Python,则可以将整个内容视为字节,包括换行符字节(表示为
\n

如果希望按字面打印换行符,请解码结果:

b'total 67092\n-rw-r--r--  1 root root      171 May 27 09:08 new.py\n-rw-r--r--  1   
    root root       74 May 12 18:14 abcd.conf\n-rwxr-xr-x  1 root root     5948 May 13 13:21 abxyz.sh\ndrwxr-xr-x  2 root root     4096 May 13
12:39 log\ndrwxrwxrwx  3 root root     4096 May 14 16:02
newpy\n-rw-r--r--  1 root root      134 May 27 10:13
pipe.py\n-rw-r--r--  1 root root      155 May 27 10:07
proc.py\ndrwxrwxrwx  3 root root     4096 May 14 14:29 py\ndrwxr-xr-x
16 1000 1000\n' b''

哦。我看到它没有打印。它直接显示在我的屏幕上。我以为我在打印它。当我在没有管道的情况下使用
stdin
时会发生什么?同样在使用
stdout=PIPE
后,它也不会在屏幕上显示stderr,为什么?它不应该只对stdout和display stderr进行管道传输。
ls
写入
stdout
文件句柄,当您不进行管道传输时,该句柄直接连接到终端。当您将它导入Python时,您正在捕获任何
ls
写入它的内容
ls
没有向
stderr
写入任何内容。当您对
stderr
使用
PIPE
时,您会看到
err
变量为空(
b'
是一个空字节值)。如果我在Popen和
print(err)
中不使用
stderr=PIPE
,则
err
的输出中会得到
None
。我的问题是为什么这个
None
不能直接显示在屏幕上。因为它是在没有stdout和stderr管道的情况下显示的。您没有捕获stderr,所以python返回None,因为需要一个值。ls没有打印任何内容;None是表示空值的Python值。
print(out.decode('utf8'))