is there a way to start/stop linux processes with python?

后端 未结 6 735
你的背包
你的背包 2021-01-05 02:31

I want to be able to start a process and then be able to kill it afterwards

相关标签:
6条回答
  • 2021-01-05 02:48

    A simple function that uses subprocess module:

    def CMD(cmd) :
        p = subprocess.Popen(cmd, shell=True,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             close_fds=False)
        return (p.stdin, p.stdout, p.stderr)
    
    0 讨论(0)
  • 2021-01-05 02:52

    Have a look at the subprocess module. You can also use low-level primitives like fork() via the os module.

    0 讨论(0)
  • 2021-01-05 02:56

    http://docs.python.org/library/os.html#process-management

    0 讨论(0)
  • 2021-01-05 02:56

    If you need to interact with the sub process at all, I recommend the pexpect module (link text). You can send input to the process, receive (or "expect") output in return, and you can close the process (with force=True to send SIGKILL).

    0 讨论(0)
  • 2021-01-05 03:08

    Here's a little python script that starts a process, checks if it is running, waits a while, kills it, waits for it to terminate, then checks again. It uses the 'kill' command. Version 2.6 of python subprocess has a kill function. This was written on 2.5.

    import subprocess
    import time
    
    proc = subprocess.Popen(["sleep", "60"], shell=False)
    print 'poll =', proc.poll(), '("None" means process not terminated yet)'
    time.sleep(3)
    subprocess.call(["kill", "-9", "%d" % proc.pid])
    proc.wait()
    print 'poll =', proc.poll()
    

    The timed output shows that it was terminated after about 3 seconds, and not 60 as the call to sleep suggests.

    $ time python prockill.py 
    poll = None ("None" means process not terminated yet)
    poll = -9
    
    real    0m3.082s
    user    0m0.055s
    sys 0m0.029s
    
    0 讨论(0)
  • 2021-01-05 03:08

    see docs for primitive fork() and modules subprocess, multiprocessing, multithreading

    0 讨论(0)
提交回复
热议问题