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.

2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
2

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)

Comments

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())

1 Comment

Where do I start my external process?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.