14

Through my web interface I would like to start/stop certain processes and determine whether a started process is still running.

My existing website is Python based and running on a Linux server, so do you know of a suitable library that supports this functionality?

Thanks

hoju
  • 28,392
  • 37
  • 134
  • 178

8 Answers8

15

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
>>>
Raghuveer
  • 1,737
  • 20
  • 27
Giampaolo Rodolà
  • 12,488
  • 6
  • 68
  • 60
6

Checking the list of running processes is accomplished (even by core utilities like "ps") by looking at the contents of the /proc directory.

As such, the library you're interested for querying running processes is the same as used for working with any other files and directories (i.e. sys or os, depending on the flavor you're after. Pay special attention to os.path though, it does most of what you're after). To terminate or otherwise interact with processes, you send them signals, which is accomplished with os.kill. Finally, you start new processes using os.popen and friends.

tylerl
  • 30,197
  • 13
  • 80
  • 113
3

Since you said this is a Linux server, calling the external ps binary is usually slower, uses more resources and is more error prone than using the information from /proc directly.

Since nobody else mentioned, one simple way is:

glob.glob('/proc/[0-9]*/')

Good luck.

Yves Junqueira
  • 755
  • 6
  • 18
2

This is what i use. It uses procfs (so you are limited to Unix like systems, will not work on macs i think) and the previously mentioned glob. It also gets the cmdline, which allows you to identify the process. For killing the process you can use os.kill(signal.SIGTERM, pid). For using subprocess, please check this post Python, Popen and select - waiting for a process to terminate or a timeout

def list_processes():
    """
    This function will return an iterator with the process pid/cmdline tuple

    :return: pid, cmdline tuple via iterator
    :rtype: iterator

    >>> for procs in list_processes():
    >>>     print procs
    ('5593', '/usr/lib/mozilla/kmozillahelper')
    ('6353', 'pickup -l -t fifo -u')
    ('6640', 'kdeinit4: konsole [kdeinit]')
    ('6643', '/bin/bash')
    ('7451', '/usr/bin/python /usr/bin/ipython')
    """
    for pid_path in glob.glob('/proc/[0-9]*/'):

        # cmdline represents the command whith which the process was started
        f = open("%s/cmdline" % pid_path)
        pid = pid_path.split("/")[2] # get the PID
        # we replace the \x00 to spaces to make a prettier output from kernel
        cmdline = f.read().replace("\x00", " ").rstrip()
        f.close()

        yield (pid, cmdline)
Community
  • 1
  • 1
1

The os module is probably your friend. There's os.kill, for instance to kill a process.

In terms of getting a list of processes, you'll probably want to shell out to the ps command. This question has more information on that.

Community
  • 1
  • 1
Schof
  • 6,329
  • 5
  • 28
  • 38
  • yeah I am ideally after a higher level library than manually parsing ps – hoju Nov 10 '09 at 01:43
  • 2
    Running the `ps` command inside a shell is a lot more dangerous than tylerl's note about using /proc. Do that instead. – Paul McMillan Nov 10 '09 at 01:43
  • because it's bad practice that leads to worse practice. First you run the `ps` command. Then you figure you want to pass a few switches to it. Then maybe a user-supplied filter string, and then you have a rooted webserver. Also, it encourages using `kill` which has the same problem. – Paul McMillan Nov 10 '09 at 02:28
  • Not sure about "encourages using kill" because there's os.kill, which means you should never have to shell out to the actual "kill" command. However, the /proc idea is definitely better than shelling out to ps, and I recommend doing that instead of my idea. – Schof Nov 14 '09 at 01:08
0

Python subprocess http://docs.python.org/library/subprocess.html might help you. If you create a process with subprocess, you can use Popen.terminate() function to stop it.

LNK2019
  • 685
  • 1
  • 6
  • 13
0

I'd use PSutil. To provide a practical example:

import psutil

for proc in psutil.get_process_list():
    if proc.username == 'yourusername':
        if myappname in proc.cmdline:
            print 'App is running'

Alternatively, Red Hat use and maintain a Python module called python-linux-procfs , which natively parses /proc, to manage processes. it's not very well publicized, but provides some additional Linux-specific features (eg, scheduling class) which are sometimes useful.

http://pkgs.fedoraproject.org/gitweb/?p=python-linux-procfs.git

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
0

Explore Supervisor which is a Python based process control system for Linux. It gives a web based UI to check the process status/start/stop/restart automatically on crash. Also there are superlance plugins available where you can send mail in case of process crash.

Sourabh Potnis
  • 1,431
  • 1
  • 17
  • 26