- How to check which specific processes (Python scripts) are running?
- 3 Answers 3
- You must log in to answer this question.
- Related
- Hot Network Questions
- Subscribe to RSS
- Process List on Linux Via Python
- How to get list of PID for all the running process with python code?
- Find processes by command in python
- Which is the best way to get a list of running processes in unix with python?
- How to list all types (running, zombie, etc.) of processes currently in linux with native python library
- How do I show a list of processes for the current user using python?
- How to find pid of a process by Python?
- How to get the process name by pid in Linux using Python?
- Process list on Linux via Python
- Prerequisites
- Steps
- Step 1: Importing the necessary modules
- Step 2: Retrieving the process list
- Step 3: Formatting the process list
- Step 4: Printing the process list
- Conclusion
How to check which specific processes (Python scripts) are running?
Using the command ‘top’ I can see 2 python scripts are running. However, how do I check their names or directory/location? I want to identify them so I can see what is running properly and what isn’t.
lsof -p $PID would be a good start. $PID can also be a comma-delimited list of PIDs. Also, tons of data will be exposed in /proc/$PID/ .
3 Answers 3
You can get a list of python processes using pgrep :
This, however, does not list the whole command line. If you have a recent version of pgrep you can use -a to do this:
Otherwise, you can use /proc :
IFS=" " read -ra pids < <(pgrep -f python) for pid in "$"; do printf '%d: ' "$pid" tr '\0' ' ' < "/proc/$pid/cmdline" echo done
I usually use ps -fA | grep python to see what processes are running.
This will give you results like the following:
UID PID PPID C STIME TTY TIME BIN CMD user 3985 3960 0 19:46 pts/4 00:00:07 path/to/python python foo.py
The CMD will show you what python scripts you have running, although it won't give you the directory of the script.
import psutil def check_process_status(process_name): """ Return status of process based on process name. """ process_status = [ proc for proc in psutil.process_iter() if proc.name() == process_name ] if process_status: for current_process in process_status: print("Process id is %s, name is %s, staus is %s"%(current_process.pid, current_process.name(), current_process.status())) else: print("Process name not valid", process_name)
You must log in to answer this question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541
Linux is a registered trademark of Linus Torvalds. UNIX is a registered trademark of The Open Group.
This site is not affiliated with Linus Torvalds or The Open Group in any way.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Process List on Linux Via Python
On linux, the easiest solution is probably to use the external ps command:
>>> import os
>>> data = [(int(p), c) for p, c in [x.rstrip('\n').split(' ', 1) \
. for x in os.popen('ps h -eo pid:1,command')]]
On other systems you might have to change the options to ps .
Still, you might want to run man on pgrep and pkill .
How to get list of PID for all the running process with python code?
If you are on Linux just use subprocess.Popen to spawn the ps - ef command, and then fetch the second column from it. Below is the example.
import subprocess as sb
proc_list = sb.Popen("ps -ef | awk ' ' ", stdout=sb.PIPE).communicate()[0].splitlines()
for pid in proc_list:
print(pid)
If you want to keep it platform independent use psutil.pids() and then iterate over the pids. You can read more about it here, it has bunch of examples which demonstrates what you are probably trying to achieve.
Please execuse any typo if any, i am just posting this from mobile device.
If you want a dictionary with pid and process name, you could use the following code:
import psutil
dict_pids = p.info["pid"]: p.info["name"]
for p in psutil.process_iter(attrs=["pid", "name"])
>
Find processes by command in python
import psutil
proc_iter = psutil.process_iter(attrs=["pid", "name", "cmdline"])
other_script_running = any("otherscript.py" in p.info["cmdline"] for p in proc_iter)
Which is the best way to get a list of running processes in unix with python?
This works on Mac OS X 10.5.5. Note the capital -U option. Perhaps that's been your problem.
import subprocess
ps = subprocess.Popen("ps -U 0", shell=True, stdout=subprocess.PIPE)
print ps.stdout.read()
ps.stdout.close()
ps.wait()
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
How to list all types (running, zombie, etc.) of processes currently in linux with native python library
Not exactly what you are trying to accomplish but linux commands can be run using the subprocess module:
import subprocess
proc = subprocess.Popen("pstree",stdout=subprocess.PIPE)
proc.communicate()[0]
proc = subprocess.Popen(["ps" ,"aux"],stdout=subprocess.PIPE)
proc.communicate()[0]
How do I show a list of processes for the current user using python?
import subprocess
ps = subprocess.Popen('ps -ef', shell=True, stdout=subprocess.PIPE)
print ps.stdout.readlines()
How to find pid of a process by Python?
If you just want the pid of the current script, then use 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.
#!/usr/bin/env python
import time
time.sleep(100)
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'))
$ 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 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
This will list the processes.
But if you want to get process name by ID, you can try ps -o cmd=
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)
Process list on Linux via Python
If you’re working on a Linux server or machine, it’s important to understand how to view the running processes. In this guide, we’ll go over the steps to obtain a process list on Linux via Python.
Prerequisites
Steps
Step 1: Importing the necessary modules
First, we need to import the necessary modules to work with processes in Linux. We’ll be using the `subprocess` module to execute Linux commands and retrieve the process list.
Step 2: Retrieving the process list
Now that we have the necessary module imported, we can execute the `ps` command to retrieve the process list. We’ll use `subprocess.check_output()` to execute the command and retrieve the output.
process_list = subprocess.check_output(['ps', '-aux'])
Step 3: Formatting the process list
The process list retrieved from the `ps` command will be a byte string. We need to convert it to a string and split it into lines to make it easier to work with. We’ll also remove the first line, which contains the column headers.
process_list = process_list.decode().split('\n')[1:]
Step 4: Printing the process list
Finally, we can print the process list to the console to view the running processes.
for process in process_list: print(process)
Conclusion
In this guide, we went over the steps to obtain a process list on Linux via Python. We used the `subprocess` module to execute the `ps` command and retrieve the process list. We then formatted the output and printed it to the console. With this knowledge, you can now view the running processes on a Linux machine with Python.