python - 优雅地退出 Python 中的程序?

标签 python

我有一个脚本作为

while True:
  doStuff()

如果我需要停止它但又不想在操作过程中终止它,那么与此脚本通信的最佳方式是什么?

最佳答案

我假设你的意思是从 python 脚本外部进行杀戮。

我发现最简单的方法是

@atexit.register
def cleanup()
  sys.unlink("myfile.%d" % os.getpid() )

f = open("myfile.%d" % os.getpid(), "w" )
f.write("Nothing")
f.close()
while os.path.exists("myfile.%d" % os.getpid() ):
  doSomething()

然后要终止脚本,只需删除 myfile.xxx,应用程序就会为您退出。如果您只需要关闭一个脚本,您甚至可以同时运行同一脚本的多个实例。它会尝试自行清理....

关于python - 优雅地退出 Python 中的程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2105509/

相关文章:

python - Sphinx Autodoc 从文档字符串中跳过成员

python - 自动化终端条目

python - JSON对象无法解码

python - 创建一个列出值的数据透视表

python - 如何比较忽略 nans 的 numpy 数组?

python - 添加箭头到股票图表

java - Python 与 Java -xms 和 -xmx

python - Pandas 每列数据框中的唯一数

python - Celery/RabbitMQ unacked 消息阻塞队列?

python - 用逆矩阵替换矩阵的所有元素