The simple python3 program named print-pid.py is running :
cat print-pid.py
import os
from time import sleep
print('my pid is',os.getpid())
sleep(1000)
The output for python3 print-pid.py
is :
my pid is 5421
To get the pid with bash command.
ps aux|grep 'python3 print-pid.py'|grep -v grep |awk '{print $2}'
5421
I wan to get the pid of the program python3 print-pid.py when it is running with python's sbuprocess module.
It is my try here:
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)
The result confued me.
CompletedProcess(args="ps aux|grep 'python3 print-pid.py'|grep -v grep |awk '{print $2}'", returncode=0, stdout=b''
The eturncode=0
means my bash command execute successfully,why stdout=b''
instead of stdout=b'5421'
?
Thank for Allan's replace and test suggestion in the comment.
For the bash command ps aux|grep 'python3'
:
import subprocess
cmd = "ps aux|grep 'python3'"
result = subprocess.run(cmd, stdout=subprocess.PIPE,shell=True)
print(result)
the output is:
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')
However for the bash command 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)
the output:
CompletedProcess(args="ps aux|grep 'python3 print-pid.py'", returncode=1, stdout=b'')
Why isn't it printing?
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'