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
每次列出后换行。但是如果使用 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''
在 subprocess.Popen
的情况下,PIPE
是如何工作的?我们为什么需要它?我也没有使用它就得到了正确的输出?我们是否使用它来同时获取 stderr 和 stdout?
最佳答案
删除 print()
调用以查看差异。
当您不将 ls
输出通过管道传输到 Python 时,它会直接显示在您的终端上;它的输出到您的终端。如果将其通过管道传输到 Python,您会看到整个内容都是字节,包括换行符字节(表示为 \n
)。
如果您希望按字面打印换行符,则对结果进行解码:
print(out.decode('utf8'))
关于python - 为什么我们应该在 subprocess.Popen 中使用 stdout=PIPE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16771117/