[英]why should we use stdout=PIPE in subprocess.Popen?
from subprocess import PIPE,Popen
p = Popen("ls -l",shell=True,stderr=PIPE,stdout=PIPE)
(out,err) = p.communicate()
print(out, err)
In above Popen call, if I remove stdout=PIPE
, I am getting newline after every listing by ls -l
in output. 在上面的Popen调用中,如果删除
stdout=PIPE
,则在输出中通过ls -l
列出的每个列表之后都会得到换行符。 But if use stdout=PIPE
, I get \\n
displayed, rather than newline, as below 但是,如果使用
stdout=PIPE
,则会显示\\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''
How does PIPE
exactly works in case of subprocess.Popen
? 如何
PIPE
正是在工作的情况下, subprocess.Popen
? Why do we need it? 我们为什么需要它? I got proper output without using it also?
我也没有使用它就得到了正确的输出? Are we using this for getting both stderr, stdout?
我们是否正在使用它同时获取stderr和stdout?
Remove the print()
call to see the difference. 删除
print()
调用以查看区别。
When you do not pipe the ls
output to Python, it is instead displayed on your terminal directly; 当您不将
ls
输出通过管道传递给Python时,它会直接显示在您的终端上。 it's output goes to your terminal. 它的输出将发送到您的终端。 If you pipe it to Python, you get to see the whole contents as bytes, including newline bytes (represented as
\\n
). 如果将其通过管道传输到Python,则会看到整个内容以字节为单位,包括换行符字节(表示为
\\n
)。
Decode the results if you want the newlines to be printed literally: 如果希望换行符按原样打印,请对结果进行解码:
print(out.decode('utf8'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.