pythonlinuxsubprocessexternal-process

Start and Stop external process from python


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.


Solution

  • 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