English 中文(简体)
Python library for Linux process management [closed]
原标题:

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 2 years ago.

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

最佳回答

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
>>>
问题回答

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.

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.

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)

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.

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.

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

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.





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签