用python杀死进程

我需要做一个脚本,从用户获得以下内容:

1)进程名称(在Linux上)。

2)这个进程写入的日志文件名。

它需要杀死进程并确认进程已closures。 将日志文件名称更改为具有时间和date的新文件名称。 然后再次运行该进程,确认它已经启动,以便继续写入日志文件。

先谢谢您的帮助。

您可以使用pgrep命令来检索给定名称的进程ID(PID),如下所示:

 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. 

希望这可以帮助

如果你知道如何在终端上做到这一点,那么你可以使用以下方法:

 import os os.system("your_command_here; second_command; third; etc") 

所以你最终有一个在python内部的小型shell脚本。 我也会考虑使这个shell脚本自己存在,然后从python中调用它:

 import os os.system("path/to/my_script.sh") 

干杯!