Search code examples
pythonbashsubprocesstimeoutterminate

How to open a subprocess (within a python script) in new terminal and kill it after 15 seconds (Platform: Ubuntu)


I am trying to start a subprocess in a new window from a python script file - timeout for 15 seconds then terminate that process without closing the main terminal window.

this is what I have so far...

cmd=subprocess.Popen('file_name.sh')
subprocess.Popen('gnome terminal -c cmd')
time.sleep(15)
Popen.terminate(cmd)

Solution

  • Try this :

    import subprocess
    import time
    
    proc = subprocess.Popen(('gnome-terminal', '--', 'file_name.sh')) 
    time.sleep(15)
    subprocess.Popen(('pkill', '-f', 'file_name.sh'))