Archive

Posts Tagged ‘kill’

Terminate a script after X seconds

December 8, 2012 Leave a comment

Problem
In Qt, there is a class called QTimer. With QTimer you can, for instance, terminate your application in X seconds. Example:

#!/usr/bin/env python

import sys

from PySide.QtCore import *
from PySide.QtGui import *

SEC = 1000    # 1 sec. is 1000 msec.

def main():
    app = QApplication(sys.argv)
    form = QDialog()
    form.show()
    # suicide in 3 seconds:
    QTimer.singleShot(3 * SEC, app.quit)
    app.exec_()

if __name__ == "__main__":
   main()

Question: how to have the same effect in a command-line application?

Solution
I came up with the following solution:

#!/usr/bin/env python

import sys
from time import sleep
import signal

class MyTimer(object):
    """
    Similar to Qt's QTimer. Call a function in a specified time.

    Time is given in sec. Usage:
    mt = MyTimer()
    mt.singleShot(<sec>, <function_name>)

    After setting it, you can still disable it:
    mt.disable()

    If you call it several times, any previously scheduled alarm
    will be canceled (only one alarm can be scheduled at any time).
    """
    def singleShot(self, sec, func):
        self.f = func
        signal.signal(signal.SIGALRM, self.handler)
        signal.alarm(sec)

    def handler(self, *args):
        self.f()

    def disable(self):
        signal.alarm(0)

def main():
    while True:
        print '.',
        sleep(0.5)
        
if __name__ == "__main__":
    mt = MyTimer()
    mt.singleShot(3, sys.exit)
    main()

As can be seen, the main function has an eternal loop. However, this program will terminate in 3 seconds. I’m imitating QTimer’s singleshot. The differences: (1) you must create a MyTimer object, and (2) time is given in seconds, not in milliseconds. You can also write it in one line if you want: MyTimer().singleShot(3, sys.exit).

It is written in a general form, so instead of sys.exit, you can also call a different function.

Handle CTRL+C in your script

November 21, 2012 Leave a comment

Question

In your script you want to handle the SIGINT signal, i.e. when the user wants to stop the script with CTRL+C, you want to call a function to handle the situation.

Answer

Here is an example:

#!/usr/bin/env python

import signal
import time

def sigint_handler(signum, frame):
    print 'Stop pressing the CTRL+C!'

signal.signal(signal.SIGINT, sigint_handler)

def main():
    while True:
       print '.'
       time.sleep(1)

##########

if __name__ == "__main__":
    main()

Now the script is immune against CTRL+C. You will have to kill it (“kill <PID>”) if you want to stop it.

If you want protection against “kill <PID>”, handle the SIGTERM signal too :)

psutil: a cross-platform process and system utilities module

November 30, 2011 Leave a comment

psutil is a module providing an interface for retrieving information on all running processes and system utilization (CPU, disk, memory) in a portable way by using Python, implementing many functionalities offered by command line tools such as: ps, top, df, kill, free, lsof, netstat, ifconfig, nice, ionice, iostat, iotop, uptime, tty. It currently supports Linux, Windows, OSX and FreeBSD both 32-bit and 64-bit with Python versions from 2.4 to 3.3 by using a single code base.” (source)

Example
Let’s kill a process by name:

# http://stackoverflow.com/questions/2940858/kill-process-by-name-in-python
import psutil

PROCNAME = 'chromedriver'

def kill_chromedriver():
    for proc in psutil.process_iter():
        if proc.name == PROCNAME:
            proc.kill()
Categories: python Tags: , ,
Design a site like this with WordPress.com
Get started