Skip to main content
 首页 » 编程设计

python之设置一个python进程名称

2025年05月04日14mengfanrong

我的 python 脚本需要每小时以及在我需要重新启动它之后被终止。我需要这样做,因为有时(我创建屏幕截图)浏览器窗口可能会因为用户登录弹出窗口或其他原因而挂起。无论如何。我创建了 2 个文件“reload.py”和“screenshot.py”。我通过 cronjob 运行 reload.py。

我认为这样的事情会奏效

    # kill process if still running 
try :    
        os.system("killall -9 screenshotTaker"); 
except : 
        print 'nothing to kill' 
 
# reload or start process 
os.execl("/path/to/script/screenshots.py", "screenshotTaker") 

问题是,我读到的 execl 的第二个参数(给定的进程名称)不起作用?我如何为其设置进程名称以使 kill 正常工作?

提前致谢!

请您参考如下方法:

os.execl 的第一个参数是可执行文件的路径。其余参数将传递给该可执行文件,就好像它们在命令行中键入的位置一样。

如果你想让“screenshotTaker”成为进程的名字,那就是“screenshots.py”有责任这样做。你在那个剧本中做了一些特别的事情吗?

顺便说一句,一种更常见的方法是跟踪(通常在/var/run/中)正在运行的程序的 PID。并通过PID杀死它。这可以用 Python 来完成(使用 os.kill )在系统级,一些发行版有用于这个确切目的的助手。例如,在 Debian 上有 start-stop-daemon。这是男人的摘录:

start-stop-daemon(8)            dpkg utilities            start-stop-daemon(8) 
 
NAME 
       start-stop-daemon - start and stop system daemon programs 
 
SYNOPSIS 
       start-stop-daemon [options] command 
 
DESCRIPTION 
       start-stop-daemon  is  used  to control the creation and termination of 
       system-level  processes.   Using   one   of   the   matching   options, 
       start-stop-daemon  can  be  configured  to find existing instances of a 
       running process.