Python Forum

Full Version: How to get the program's pid which is running with subprocess module?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The simple python3 program named print-pid.py is running :

import os 
from time import sleep  
print('my pid is',os.getpid())
sleep(1000)
The result is :
my pid is 5481

To get the pid with bash command(open a new terminal to run).
#bash code
ps aux|grep 'python3 print-pid.py'|grep -v grep |awk '{print $2}'
5481
I want 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)
CompletedProcess(args="ps aux|grep 'python3 print-pid.py'|grep -v grep |awk '{print $2}'", returncode=0, stdout=b''

The returncode is 0 means the bash cmd executed well in subprocess,why stdout is not stdout=b'5481' ?
does it have to be with subprocess? Look at psutils