Linux посмотреть процессы python

Process list on Linux via Python

IMO looking at the /proc filesystem is less nasty than hacking the text output of ps .

import os pids = [pid for pid in os.listdir('/proc') if pid.isdigit()] for pid in pids: try: print open(os.path.join('/proc', pid, 'cmdline'), 'rb').read().split('\0') except IOError: # proc has already terminated continue 

You will have to surround the read() call with a try/except block as a pid returned from reading os.listdir(‘/proc’) may no longer exist by the time you read the cmdline.

Watch out: the command line is terminated by 0x00. Whitespaces are also replaced with the same character.

Just use psutil — it does all this through a nice Pythonic interface and is portable if you ever want to run on a non-Linux server.

You could use psutil as a platform independent solution!

import psutil psutil.pids() [1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224, 268, 1215, 1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355, 2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245, 4263, 4282, 4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358, 4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446, 5167, 5234, 5235, 5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071] 

It’s not completely platform independent — on OSX you can run into AccessDenied errors: groups.google.com/forum/?fromgroups=#!topic/psutil/bsjpawhiWms

@amos kinda makes sense — you’d want to have privileges in place first before reaching out to information about processes. Thanks for the hint.

The sanctioned way of creating and using child processes is through the subprocess module.

import subprocess pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0] print pl 

The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply ‘ps -U 0’ to Popen.

Читайте также:  Linux what directory to install

You can use a third party library, such as PSI:

PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.

PSI was last updated in 2009, whereas psutil was updated this month (Nov 2015) — seems like psutil is a better bet.

I would use the subprocess module to execute the command ps with appropriate options. By adding options you can modify which processes you see. Lot’s of examples on subprocess on SO. This question answers how to parse the output of ps for example:)

You can, as one of the example answers showed also use the PSI module to access system information (such as the process table in this example).

from psutil import process_iter from termcolor import colored names = [] ids = [] x = 0 z = 0 k = 0 for proc in process_iter(): name = proc.name() y = len(name) if y>x: x = y if y 

Welcome to StackOverflow. While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.

This code is poorly written, needlessly complex, and unpythonic. It is not a good example of how to achieve this.

Источник

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.

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.14.43533

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)

Источник

Оцените статью
Adblock
detector