我有一个Python脚本,我想让它重新启动。我发现以下几行谷歌搜索:
def restart_program():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
python = sys.executable
os.execl(python, python, * sys.argv)
但是在尝试这个问题之后问题就变得明显了。我正在运行一个非常小的嵌入式系统,而且我的内存耗尽非常快(在此功能的两次或三次迭代之后)。检查进程列表,我可以看到一大堆python进程。 现在,我意识到,我可以检查进程列表并杀死所有具有另一个PID的进程而不是我自己 - 这是我必须做的还是有更好的Python解决方案?
答案 0 :(得分:2)
这会使用用于生成第一个进程的相同调用生成一个新的子进程,但它不会停止现有进程(更准确地说:现有进程等待子进程退出)。
更简单的方法是重构您的程序,这样您就不必重新启动它。你为什么需要这样做?
答案 1 :(得分:1)
我重新编写了我的重启函数,如下所示,在启动新的子进程之前,它会杀死除自身之外的每个python进程:
def restart_program():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
logger.info("RESTARTING SCRIPT")
# command to extract the PID from all the python processes
# in the process list
CMD="/bin/ps ax | grep python | grep -v grep | awk '{ print $1 }'"
#executing above command and redirecting the stdout int subprocess instance
p = subprocess.Popen(CMD, shell=True, stdout=subprocess.PIPE)
#reading output into a string
pidstr = p.communicate()[0]
#load pidstring into list by breaking at \n
pidlist = pidstr.split("\n")
#get pid of this current process
mypid = str(os.getpid())
#iterate through list killing all left over python processes other than this one
for pid in pidlist:
#find mypid
if mypid in pid:
logger.debug("THIS PID "+pid)
else:
#kill all others
logger.debug("KILL "+pid)
try:
pidint = int(pid)
os.kill(pidint, signal.SIGTERM)
except:
logger.error("CAN NOT KILL PID: "+pid)
python = sys.executable
os.execl(python, python, * sys.argv)
不确定这是否是最佳解决方案,但无论如何都适用于临时......