Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中程序的优雅退出?_Python - Fatal编程技术网

Python中程序的优雅退出?

Python中程序的优雅退出?,python,Python,我有一个脚本,作为 while True: doStuff() 如果我需要停止这个脚本,最好的方法是什么?但是如果它在操作的中间,我不想杀死它。 < P>我认为最优雅的是: keep_running = true while keep_running: dostufF() 然后,dostuff()可以设置keep_running=false,只要in不再想继续运行,while循环就会结束,一切都会很好地清理干净。最好的方法是重写脚本,这样它就不会使用while True: 可悲的

我有一个脚本,作为

while True:
  doStuff()

如果我需要停止这个脚本,最好的方法是什么?但是如果它在操作的中间,我不想杀死它。

< P>我认为最优雅的是:

keep_running = true
while keep_running:
    dostufF()

然后,
dostuff()
可以设置
keep_running=false
,只要in不再想继续运行,while循环就会结束,一切都会很好地清理干净。

最好的方法是重写脚本,这样它就不会使用
while True:

可悲的是,我们不可能推测出一个好的方法来终止这一切

您可以使用Linux信号

你可以用定时器,过一会儿就停下来

您可以让
dostuff
返回一个值,如果该值为
False
则停止

您可以检查本地文件,并在该文件存在时停止

您可以检查FTP站点是否存在远程文件,并停止该文件

您可以检查HTTP网页以获取指示循环是否应该停止的信息


您可以使用特定于操作系统的东西,如信号量或共享内存。

如果这是一个控制台应用程序,按Ctrl+C退出可以,这能解决您的问题吗

try:
  while True:
    doStuff()
except KeyboardInterrupt:
  doOtherStuff()

我想这种方法的问题在于,您无法准确地控制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,应用程序就会为您退出。即使同一脚本的多个实例同时运行,如果只需要关闭一个实例,也可以使用它。它试图在自己之后进行清理……

信号模块可以捕获信号并做出相应的反应?

感谢您的快速回答,肯定有一些我没有想到的好主意。