psutil là thư viện đa nền tảng truy xuất thông tin về các quy trình đang chạy và sử dụng hệ thống.
import psutil
pythons_psutil = []
for p in psutil.process_iter():
try:
if p.name() == 'python.exe':
pythons_psutil.append(p)
except psutil.Error:
pass
>>> pythons_psutil
[<psutil.Process(pid=16988, name='python.exe') at 25793424>]
>>> print(*sorted(pythons_psutil[0].as_dict()), sep='\n')
cmdline
connections
cpu_affinity
cpu_percent
cpu_times
create_time
cwd
exe
io_counters
ionice
memory_info
memory_info_ex
memory_maps
memory_percent
name
nice
num_ctx_switches
num_handles
num_threads
open_files
pid
ppid
status
threads
username
>>> pythons_psutil[0].memory_info()
pmem(rss=12304384, vms=8912896)
Trong một cổ phiếu của Windows Python bạn có thể sử dụng subprocess
và csv
để phân tích đầu ra của tasklist.exe
:
import subprocess
import csv
p_tasklist = subprocess.Popen('tasklist.exe /fo csv',
stdout=subprocess.PIPE,
universal_newlines=True)
pythons_tasklist = []
for p in csv.DictReader(p_tasklist.stdout):
if p['Image Name'] == 'python.exe':
pythons_tasklist.append(p)
>>> print(*sorted(pythons_tasklist[0]), sep='\n')
Image Name
Mem Usage
PID
Session Name
Session#
>>> pythons_tasklist[0]['Mem Usage']
'11,876 K'
Dưới đây là cách thực hiện các quy trình đang chạy trên Windows: http://timgolden.me.uk/python/wmi/cookbook.html#list-all-running-processes - và đây là cách để có được thông tin quy trình đang chạy trên OSX: http://stackoverflow.com/questions/1673874/how-can-i-get-the-full-list-of-running-processes-on-a-mac-from-a-python-app – Acorn