Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kill process with python

I need to make a script that gets from the user the following:

1) Process name (on linux).

2) The log file name that this process write to it.

It needs to kill the process and verify that the process is down. Change the log file name to a new file name with the time and date. And then run the process again, verify that it's up in order it will continue to write to the log file.

Thanks in advance for the help.

like image 386
Bar Aviv Avatar asked Nov 18 '10 12:11

Bar Aviv


People also ask

How do you kill PID in Python?

You can kill a process via its process identifier, pid, via the os. kill() function.

What is the kill command in Python?

kill() method in Python is used to send specified signal to the process with specified process id. Constants for the specific signals available on the host platform are defined in the signal module. Parameters: pid: An integer value representing process id to which signal is to be sent.

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.


1 Answers

You can retrieve the process id (PID) given it name using pgrep command like this:

import subprocess
import signal
import os
from datetime import datetime as dt


process_name = sys.argv[1]
log_file_name = sys.argv[2]


proc = subprocess.Popen(["pgrep", process_name], stdout=subprocess.PIPE) 

# Kill process.
for pid in proc.stdout:
    os.kill(int(pid), signal.SIGTERM)
    # Check if the process that we killed is alive.
    try: 
       os.kill(int(pid), 0)
       raise Exception("""wasn't able to kill the process 
                          HINT:use signal.SIGKILL or signal.SIGABORT""")
    except OSError as ex:
       continue

# Save old logging file and create a new one.
os.system("cp {0} '{0}-dup-{1}'".format(log_file_name, dt.now()))

# Empty the logging file.
with open(log_file_name, "w") as f:
    pass

# Run the process again.
os.sytsem("<command to run the process>") 
# you can use os.exec* if you want to replace this process with the new one which i think is much better in this case.

# the os.system() or os.exec* call will failed if something go wrong like this you can check if the process is runninh again.

Hope this can help

like image 144
mouad Avatar answered Sep 19 '22 18:09

mouad