Python library for Linux process management
To start/stop python sub processes you can use the subprocess module.
To check whether they are running you might use psutil:
>>> import psutil
>>> pid = 1034 # some pid
>>> psutil.pid_exists(pid)
True
>>>
...or this (it will also check if the PID has been reused):
>>> p = psutil.Process(pid)
>>> p.is_running()
True
>>>
is there a way to start/stop linux processes with python?
Have a look at the subprocess
module.
You can also use low-level primitives like fork()
via the os
module.
process management with python: execute service or systemd or init.d script
I found a way using systemd dbus interface. Here is the code:
import dbus
import subprocess
import os
import sys
import time
SYSTEMD_BUSNAME = 'org.freedesktop.systemd1'
SYSTEMD_PATH = '/org/freedesktop/systemd1'
SYSTEMD_MANAGER_INTERFACE = 'org.freedesktop.systemd1.Manager'
SYSTEMD_UNIT_INTERFACE = 'org.freedesktop.systemd1.Unit'
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
authority = dbus.Interface(proxy, dbus_interface='org.freedesktop.PolicyKit1.Authority')
system_bus_name = bus.get_unique_name()
subject = ('system-bus-name', {'name' : system_bus_name})
action_id = 'org.freedesktop.systemd1.manage-units'
details = {}
flags = 1 # AllowUserInteraction flag
cancellation_id = '' # No cancellation id
result = authority.CheckAuthorization(subject, action_id, details, flags, cancellation_id)
if result[1] != 0:
sys.exit("Need administrative privilege")
systemd_object = bus.get_object(SYSTEMD_BUSNAME, SYSTEMD_PATH)
systemd_manager = dbus.Interface(systemd_object, SYSTEMD_MANAGER_INTERFACE)
unit = systemd_manager.GetUnit('cups.service')
unit_object = bus.get_object(SYSTEMD_BUSNAME, unit)
#unit_interface = dbus.Interface(unit_object, SYSTEMD_UNIT_INTERFACE)
#unit_interface.Stop('replace')
systemd_manager.StartUnit('cups.service', 'replace')
while list(systemd_manager.ListJobs()):
time.sleep(2)
print 'there are pending jobs, lets wait for them to finish.'
prop_unit = dbus.Interface(unit_object, 'org.freedesktop.DBus.Properties')
active_state = prop_unit.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
sub_state = prop_unit.Get('org.freedesktop.systemd1.Unit', 'SubState')
print active_state, sub_state
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
Simple remote process monitoring with Python
The Fabric library may be of interest to you.
Windows process management using Python
On Windows, you can use WMI:
import win32com.client
def find_process(name):
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(".", "root\cimv2")
colItems = objSWbemServices.ExecQuery(
"Select * from Win32_Process where Caption = '{0}'".format(name))
return len(colItems)
print find_process("SciTE.exe")
Monitor Process in Python?
There are a couple of options,
1: the more crude but obvious would be to do some text processing against:
os.popen('tasklist').read()
2: A more involved option would be to use pywin32 and research the win32 APIs to figure out what processes are running.
3: WMI (I found this just now), and here is a vbscript example of how to query the machine for processes through WMI.
Is there a way to change effective process name in Python?
Simply put, there's no portable way. You'll have to test for the system and use the preferred method for that system.
Further, I'm confused about what you mean by process names on Windows.
Do you mean a service name? I presume so, because nothing else really makes any sense (at least to my non-Windows using brain).
If so, you need to use Tim Golden's WMI interface and call the .Change method on the service... at least according to his tutorial.
For Linux none of the methods I found worked except for this poorly packaged module that sets argv[0] for you.
I don't even know if this will work on BSD variants (which does have a setproctitle system call). I'm pretty sure argv[0] won't work on Solaris.
Total memory used by Python process?
Here is a useful solution that works for various operating systems, including Linux, Windows, etc.:
import os, psutil
process = psutil.Process(os.getpid())
print(process.memory_info().rss) # in bytes
Notes:
do
pip install psutil
if it is not installed yethandy one-liner if you quickly want to know how many MB your process takes:
import os, psutil; print(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2)
with Python 2.7 and psutil 5.6.3, it was
process.memory_info()[0]
instead (there was a change in the API later).
Related Topics
Error Installing Uwsgi in Virtualenv
What Are the Differences Between the Urllib, Urllib2, Urllib3 and Requests Module
Proper Name for Python * Operator
How to Run Functions in Parallel
Why Is Button Parameter "Command" Executed When Declared
How to Preserve Timezone When Parsing Date/Time Strings with Strptime()
Iterate Through Pairs of Items in a Python List
Creating an Empty Pandas Dataframe, Then Filling It
Make (Install from Source) Python Without Running Tests
Detect and Exclude Outliers in a Pandas Dataframe
Nested Defaultdict of Defaultdict
How to Find All the Subclasses of a Class Given Its Name
Pip Install MySQL-Python Fails with Environmenterror: MySQL_Config Not Found