Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate a python script from another python script

I've got a long running python script that I want to be able to end from another python script. Ideally what I'm looking for is some way of setting a process ID to the first script and being able to see if it is running or not via that ID from the second. Additionally, I'd like to be able to terminate that long running process.

Any cool shortcuts exist to make this happen?

Also, I'm working in a Windows environment.

I just recently found an alternative answer here: Check to see if python script is running

like image 690
Nick Avatar asked Jun 16 '10 15:06

Nick


People also ask

How do you stop a Python script from a script?

Press CTRL + C to terminate the Python script To stop a script in Python, press Ctrl + C. If you are using Mac, press Ctrl + C.

How do you stop a Python process from running?

You can use ps aux | grep python to determine the running Python processes and then use kill <pid> command for sending a SIGTERM signal to the system. To kill the program by file name: pkill -f python-script-name.


2 Answers

You're looking for the subprocess module.

import subprocess as sp

extProc = sp.Popen(['python','myPyScript.py']) # runs myPyScript.py 

status = sp.Popen.poll(extProc) # status should be 'None'

sp.Popen.terminate(extProc) # closes the process

status = sp.Popen.poll(extProc) # status should now be something other than 'None' ('1' in my testing)

subprocess.Popen starts the external python script, equivalent to typing 'python myPyScript.py' in a console or terminal.

The status from subprocess.Popen.poll(extProc) will be 'None' if the process is still running, and (for me) 1 if it has been closed from within this script. Not sure about what the status is if it has been closed another way.

like image 84
wordsforthewise Avatar answered Oct 03 '22 12:10

wordsforthewise


You could get your own PID (Process Identifier) through

import os
os.getpid()

and to kill a process in Unix

import os, signal
os.kill(5383, signal.SIGKILL)

to kill in Windows use

import subprocess as s
def killProcess(pid):
    s.Popen('taskkill /F /PID {0}'.format(pid), shell=True)

You can send the PID to the other programm or you could search in the process-list to find the name of the other script and kill it with the above script.

I hope that helps you.

like image 36
Joschua Avatar answered Oct 03 '22 12:10

Joschua