为什么returncode = 0而且我的subprocess.run没有stdout?

时间:2018-01-24 02:57:05

标签: python bash subprocess

名为print-pid.py的简单python3程序正在运行:

cat print-pid.py
import os 
from time import sleep  
print('my pid is',os.getpid())
sleep(1000)

python3 print-pid.py的输出是:

my pid is 5421

使用bash命令获取pid。

ps aux|grep 'python3 print-pid.py'|grep -v grep |awk '{print $2}'
5421

当使用python的sbuprocess模块​​运行时,我想得到程序python3 print-pid.py的pid。

这是我的尝试:

import subprocess
cmd = "ps aux|grep 'python3 print-pid.py'|grep -v grep |awk '{print $2}'"
result = subprocess.run(cmd, stdout=subprocess.PIPE,shell=True)
print(result)

结果让我感到困惑。

CompletedProcess(args =“ps aux | grep'python3 print-pid.py'| grep -v grep | awk'{print $ 2}'”,returncode = 0,stdout = b''

eturncode=0表示我的bash命令成功执行,为什么stdout=b''代替stdout=b'5421'

感谢评论中Allan的替换和测试建议。

对于bash命令ps aux|grep 'python3'

import subprocess
cmd = "ps aux|grep 'python3'"
result = subprocess.run(cmd, stdout=subprocess.PIPE,shell=True)
print(result)

输出是:

CompletedProcess(args="ps aux|grep 'python3'", returncode=0,     
stdout=b'debian9   6569  0.0  0.2  31916  9376 pts/0    S+   11:04   0:00 python3 print-p\ndebian9   6844  0.0  0.2  39860 11440 pts/2    S+   11:13   0:00 python3\ndebian9   6929  0.0  0.0  16980   948 pts/2    S+   11:17   0:00 grep python3\n') 

但是对于bash命令ps aux|grep 'python3 print-pid.py'

import subprocess
cmd = "ps aux|grep 'python3 print-pid.py'"
result = subprocess.run(cmd, stdout=subprocess.PIPE,shell=True)
print(result)

输出:

CompletedProcess(args="ps aux|grep 'python3 print-pid.py'", returncode=1, stdout=b'')

为什么不打印?

stdout=b'' instead of  stdout=b'debian9   6569  0.0  0.2  31916  9376 pts/0    S+   11:04   0:00 python3 print-p\n
debian9   6929  0.0  0.0  16980   948 pts/2    S+   11:17   0:00 grep python3 print-pid.py\n'

0 个答案:

没有答案