0

我已经搜索了我的问题的解决方案并找到了一些,但它们对我不起作用或者对于我想要实现的目标非常复杂。

我有一个使用线程创建 3 个 BaseHTTPServers 的 python (2.7) 脚本。我现在希望能够从自身关闭 python 脚本并重新启动它。为此,我使用以下内容创建了一个名为“restart_script”的额外文件:

sleep 2
python2 myScript.py

然后我启动这个脚本,然后关闭我自己的 python 脚本:

os.system("nohup bash restart_script & ")
exit()

这很好用,python 脚本关闭并在 2 秒后弹出新脚本,但 BaseHTTPServers 没有出现,报告地址已在使用中。(socket.error Errno 98)。

我启动服务器:

httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)

然后我让它永远服务:

thread.start_new_thread(httpd.serve_forever, tuple())

我也试过这个:

httpd_thread = threading.Thread(target=httpd.serve_forever)
httpd_thread.daemon = True
httpd_thread.start()

但这具有相同的结果。

如果我使用 strg+c 终止脚本,然后立即重新启动它,一切正常。我认为只要我想从它自己重新启动脚本,旧进程仍然以某种方式处于活动状态,我需要以某种方式拒绝它,以便可以清除套接字。

我在 Linux (Xubuntu) 上运行。

我怎样才能真正杀死我自己的脚本,然后在几秒钟后再次启动它,以便关闭所有套接字?

4

1 回答 1

1

我找到了我的具体问题的答案。

我只是使用另一个脚本,它使用 os.system() 启动我的主程序。如果脚本要重新启动,我只需定期关闭它,而另一个脚本只是再次启动它,一遍又一遍......

如果我想真正关闭我的脚本,我会添加一个文件并检查另一个脚本(如果该文件存在)。

重启助手脚本如下所示:

import os, time

cwd = os.getcwd()

#first start --> remove shutdown:
try:
    os.remove(os.path.join(cwd, "shutdown"))
except:
    pass

while True:
    #check if shutdown requested:
    if os.path.exists(os.path.join(cwd, "shutdown")):
        break
    #else start script:
    os.system("python2 myMainScript.py")
    #after it is done, wait 2 seconds: (just to make sure sockets are closed.. might be optional)
    time.sleep(2)
于 2014-12-08T21:41:22.583 回答