为什么我们在subprocess.Popen中使用stdout = PIPE? [英] 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)
在上面的Popen调用中,如果我删除 stdout = PIPE
,我在每个列表后得到换行符 ls -l </ code>输出。但是如果使用
stdout = PIPE
,我会显示 \\\
,而不是换行,如下
In above Popen call, if I remove stdout=PIPE
, I am getting newline after every listing by ls -l
in output. But if use stdout=PIPE
, I get \n
displayed, rather than newline, as below
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''
$ b b
PIPE
如何在 subprocess.Popen
的情况下正常工作?为什么我们需要它?我得到适当的输出,而不使用它吗?
How does PIPE
exactly works in case of subprocess.Popen
? Why do we need it? I got proper output without using it also? Are we using this for getting both stderr, stdout?
推荐答案
删除 print()
调用看到的区别。
当你不把管道 ls
输出到Python,直接显示在您的终端上;它的输出到您的终端。如果你把它管道到Python,你会看到整个内容作为字节,包括换行字节(表示为 \\\
)。
When you do not pipe the ls
output to Python, it is instead displayed on your terminal directly; 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
).
如果您希望以字面方式打印换行符,请解码结果:
Decode the results if you want the newlines to be printed literally:
print(out.decode('utf8'))
这篇关于为什么我们在subprocess.Popen中使用stdout = PIPE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!