How to display list of running processes Python?
Try this command:
ps -ef | grep python
ps
stands for process status
how do I get the process list in 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 '{print $2} ' ", 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.
Hope this helps.
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
I wonder if this works
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()
Here's the Python version
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
:
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 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)
Related Topics
Decode HTML Entities in Python String
How to Make a Python Script Run Like a Service or Daemon in Linux
How to Use "/" (Directory Separator) in Both Linux and Windows in Python
Converting Epoch Time With Milliseconds to Datetime
"Is" Operator Behaves Unexpectedly With Integers
Switch Between Two Frames in Tkinter
Why Is the Output of My Function Printing Out "None"
Finding the Index of an Item in a List
Using Python'S Eval() Vs. Ast.Literal_Eval()
How to Randomly Select an Item from a List
Strip HTML from Strings in Python
Get Total Physical Memory in Python
Integer Division by Negative Number
How to Merge Two Dictionaries in a Single Expression
Why Does Append() Always Return None in Python
How to Parse Xml and Get Instances of a Particular Node Attribute