python popen.stdout管道_为什么我们在subprocess.Popen中使用stdout = PIPE?

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. 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''

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?

解决方案

Remove the print() call to see the difference.

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'))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值