Python Forum
How to get the program's pid which is running with subprocess module?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get the program's pid which is running with subprocess module?
#1
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' ?
Reply
#2
does it have to be with subprocess? Look at psutils
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  problem in using subprocess module akbarza 5 1,018 Sep-24-2023, 02:02 PM
Last Post: snippsat
  Program running on RPi 3b+ Very Strange Behavior - Out of Bound Index MadMacks 26 3,273 Mar-07-2023, 09:50 PM
Last Post: MadMacks
  Running script with subprocess in another directory paul18fr 1 3,706 Jan-20-2023, 02:33 PM
Last Post: paul18fr
  running a TensorFlow program Led_Zeppelin 0 907 Apr-07-2022, 06:33 PM
Last Post: Led_Zeppelin
Question Setuptools CLI program ModuleNotFoundError after splitting up module into package Postbote 1 2,313 Nov-25-2021, 06:35 PM
Last Post: Postbote
  Question on subprocess module. knoxvilles_joker 3 2,680 Apr-11-2021, 12:51 AM
Last Post: knoxvilles_joker
  Python Program running a lot slower after change to Ubuntu hubenhau 1 2,886 Mar-02-2021, 05:01 PM
Last Post: Serafim
  Running Python 2.7 program ErnestTBass 2 2,766 Oct-21-2020, 08:06 AM
Last Post: snippsat
  Error when running mktorrent subprocess command pythonnewbie138 4 3,836 Sep-16-2020, 01:55 AM
Last Post: pythonnewbie138
  read terminal text from running program AArdvark_UK 2 1,882 Aug-27-2020, 12:43 PM
Last Post: AArdvark_UK

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020