3

Is there a way to start and stop a process from python? I'm talking about a continues process that I stop with ctrl+z when normally running. I want to start the process, wait for some time and then kill it. I'm using linux.

this question is not like mine because there, the user only needs to run the process. I need to run it and also stop it.

Community
  • 1
  • 1
Javi
  • 861
  • 1
  • 14
  • 40
  • Possible duplicate of: https://stackoverflow.com/questions/89228/calling-an-external-command-in-python?rq=1 – serk Aug 14 '15 at 13:10
  • I was able to do what I wanted thanks to this post http://stackoverflow.com/questions/636561/how-can-i-run-an-external-command-asynchronously-from-python – Javi Aug 14 '15 at 14:32

3 Answers3

5

I want to start the process, wait for some time and then kill it.

#!/usr/bin/env python3
import subprocess

try:
    subprocess.check_call(['command', 'arg 1', 'arg 2'],
                          timeout=some_time_in_seconds)
except subprocess.TimeoutExpired: 
    print('subprocess has been killed on timeout')
else:
    print('subprocess has exited before timeout')

See Using module 'subprocess' with timeout

Community
  • 1
  • 1
jfs
  • 346,887
  • 152
  • 868
  • 1,518
  • Elegant - avoids any need to explicitly call `kill`. However, it should be noted that this is for Python > 3.3 - to use it in Python 2.7 you need to make use of the [subprocess32 backport module](https://pypi.python.org/pypi/subprocess32/). – Aaron D Aug 15 '15 at 00:49
1

Maybe you can use Process module:

from multiprocessing import Process
import os
import time

def sleeper(name, seconds):
    print "Sub Process %s ID# %s" % (name, os.getpid())
    print "Parent Process ID# %s" % (os.getppid())
    print "%s will sleep for %s seconds" % (name, seconds)
    time.sleep(seconds)

if __name__ == "__main__":
    child_proc = Process(target=sleeper, args=('bob', 5)) 
    child_proc.start()
    time.sleep(2)
    child_proc.terminate()
    #child_proc.join()
    #time.sleep(2)
    #print "in parent process after child process join"
    #print "the parent's parent process: %s" % (os.getppid())
kaitian521
  • 430
  • 1
  • 9
  • 24
1

You can use the os.kill function to send -SIGSTOP (-19) and -SIGCONT (-18)

Example (unverified):

import signal
from subprocess import check_output

def get_pid(name):
    return check_output(["pidof",name])

def stop_process(name):
    pid = get_pid(name)
    os.kill(pid, signal.SIGSTOP)

def restart_process(name):
    pid = get_pid(name)
    os.kill(pid, signal.SIGCONT)
mplf
  • 1,995
  • 12
  • 23