Finding the command for a specific PID in Linux from Python
Using a /proc files has a disadvantage of lower portability, which may or may not be a concern. Here's how you can use the standard shell command for that
ps -w -w -p <YOUR PID> -o cmd h
Note the two -w
options that instructs ps to not truncate the output (which it does by default)
Reading its output from python is as simple as calling a single function subprocess.check_output()
documented here.
How to find pid of a process by Python?
If you just want the pid of the current script, then use os.getpid
:
import os
pid = os.getpid()
However, below is an example of using psutil to find the pids of python processes running a named python script. This could include the current process, but the main use case is for examining other processes, because for the current process it is easier just to use os.getpid
as shown above.
sleep.py
#!/usr/bin/env python
import time
time.sleep(100)
get_pids.py
import os
import psutil
def get_pids_by_script_name(script_name):
pids = []
for proc in psutil.process_iter():
try:
cmdline = proc.cmdline()
pid = proc.pid
except psutil.NoSuchProcess:
continue
if (len(cmdline) >= 2
and 'python' in cmdline[0]
and os.path.basename(cmdline[1]) == script_name):
pids.append(pid)
return pids
print(get_pids_by_script_name('sleep.py'))
Running it:
$ chmod +x sleep.py
$ cp sleep.py other.py
$ ./sleep.py &
[3] 24936
$ ./sleep.py &
[4] 24937
$ ./other.py &
[5] 24938
$ python get_pids.py
[24936, 24937]
How to get PID by process name?
You can get the pid of processes by name using pidof
through subprocess.check_output:
from subprocess import check_output
def get_pid(name):
return check_output(["pidof",name])
In [5]: get_pid("java")
Out[5]: '23366\n'
check_output(["pidof",name])
will run the command as "pidof process_name"
, If the return code was non-zero it raises a CalledProcessError.
To handle multiple entries and cast to ints:
from subprocess import check_output
def get_pid(name):
return map(int,check_output(["pidof",name]).split())
In [21]: get_pid("chrome")
Out[21]:
[27698, 27678, 27665, 27649, 27540, 27530, 27517, 14884, 14719, 13849, 13708, 7713, 7310, 7291, 7217, 7208, 7204, 7189, 7180, 7175, 7166, 7151, 7138, 7127, 7117, 7114, 7107, 7095, 7091, 7087, 7083, 7073, 7065, 7056, 7048, 7028, 7011, 6997]
Or pas the -s
flag to get a single pid:
def get_pid(name):
return int(check_output(["pidof","-s",name]))
In [25]: get_pid("chrome")
Out[25]: 27698
How to get the process name by pid in Linux using Python?
If you want to see the running process, you can just use os
module to execute the ps
unix command
import os
os.system("ps")
This will list the processes.
But if you want to get process name by ID, you can try ps -o cmd= <pid>
So the python code will be
import os
def get_pname(id):
return os.system("ps -o cmd= {}".format(id))
print(get_pname(1))
The better method is using subprocess
and pipes.
import subprocess
def get_pname(id):
p = subprocess.Popen(["ps -o cmd= {}".format(id)], stdout=subprocess.PIPE, shell=True)
return str(p.communicate()[0])
name = get_pname(1)
print(name)
How do you get the process ID of a program in Unix or Linux using Python?
Try pgrep
. Its output format is much simpler and therefore easier to parse.
How to check if there exists a process with a given pid in Python?
Sending signal 0 to a pid will raise an OSError exception if the pid is not running, and do nothing otherwise.
import os
def check_pid(pid):
""" Check For the existence of a unix pid. """
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True
Open process with specific pid in python
PIDs are given by the OS, you cannot use a specific PID for your subprocess.
To determine the PID of a subprocess, you can ask the subprocess for it:
import subprocess
dateProc = subprocess.Popen([ 'date' ])
print dateProc.pid
If you meant you want to know the PID of the current process, use os.getpid()
.
Find pid using python by grepping two variables
From the docs:
(...) On Unix, the return value is the exit status of the process encoded in the format specified for wait() (...)
And since your program runs correctly, it returns 0.
To get the desired output, you must use the subprocess
module (https://docs.python.org/3.6/library/subprocess.html#subprocess.check_output):
import subprocess
oracle_pid = subprocess.check_output("ps -ef | grep pmon | grep %s | grep -v grep | awk '{print $2}'", stderr=subprocess.STDOUT, shell=True).strip().decode("utf-8")
Related Topics
How to Prompt For User Input and Read Command-Line Arguments
Read File with Timeout in Python
How to Recover the Return Value of a Function Passed to Multiprocessing.Process
How to Organize My Tkinter Appllication
CSS Problems with Flask Web App
Selecting With Complex Criteria from Pandas.Dataframe
How to Change a Global Variable from Within a Function
Pyaudio Installation Error - 'Command 'Gcc' Failed with Exit Status 1'
Find Intersection of Two Nested Lists
How to Correctly Sort a String With a Number Inside
How to Crop an Image in Opencv Using Python
Cron Job: How to Run a Script That Requires to Open Display
What Does -≫ Mean in Python Function Definitions
Groupby Pandas Dataframe and Select Most Common Value
How to Install a Script to Run Anywhere from the Command Line
Check If All Elements in a List Are Identical
Beautiful Soup: 'Resultset' Object Has No Attribute 'Find_All'