在Python中使用超时运行某些代码的正确方法 [英] right way to run some code with timeout in Python

查看:320
本文介绍了在Python中使用超时运行某些代码的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上看了一下,发现一些SO讨论和ActiveState配方用于在超时的情况下运行某些代码.看起来有一些常见的方法:

I looked online and found some SO discussing and ActiveState recipes for running some code with a timeout. It looks there are some common approaches:

  • 使用运行代码的线程,并在超时的情况下使用join.如果超时,请杀死线程. Python(使用私有的_Thread__stop函数)不直接支持此功能,因此不好的做法
  • 使用signal.SIGALRM-但此方法在Windows上不起作用
  • 使用带有超时的子进程-但这太重了-如果我想经常启动可中断任务怎么办,我不想为每个任务都触发任务!
  • Use thread that run the code, and join it with timeout. If timeout elapsed - kill the thread. This is not directly supported in Python (used private _Thread__stop function) so it is bad practice
  • Use signal.SIGALRM - but this approach not working on Windows!
  • Use subprocess with timeout - but this is too heavy - what if I want to start interruptible task often, I don't want fire process for each!

那么,正确的方法是什么?我不是在问解决方法(例如,使用Twisted和异步IO),而是解决实际问题的实际方法-我有一些功能,我只想在超时的情况下运行它.如果超时了,我想控制住.而且我希望它可以在Linux和Windows上运行.

So, what is the right way? I'm not asking about workarounds (eg use Twisted and async IO), but actual way to solve actual problem - I have some function and I want to run it only with some timeout. If timeout elapsed, I want control back. And I want it to work on Linux and Windows.

推荐答案

对于此诚实,诚实,没有一个完全通用的解决方案.您必须为给定的域使用正确的解决方案.

A completely general solution to this really, honestly does not exist. You have to use the right solution for a given domain.

  • 如果您希望完全控制的代码超时,则必须编写代码以配合使用.这样的代码必须能够以某种方式分解成小块,例如在事件驱动的系统中.如果可以确保没有什么东西可以长时间持有锁,那么您也可以通过线程执行此操作,但是正确处理锁实际上非常困难.

  • If you want timeouts for code you fully control, you have to write it to cooperate. Such code has to be able to break up into little chunks in some way, as in an event-driven system. You can also do this by threading if you can ensure nothing will hold a lock too long, but handling locks right is actually pretty hard.

如果由于担心代码失控而想要超时(例如,如果担心用户会要求计算器计算9**(9**9)),则需要在另一个进程中运行它.这是充分隔离它的唯一简便方法.在事件系统或什至是其他线程中运行它是不够的.与其他解决方案类似,也可以将其分解成小块,但是需要非常小心的处理,通常不值得.在任何情况下,这都不允许您执行与仅运行Python代码相同的操作.

If you want timeouts because you're afraid code is out of control (for example, if you're afraid the user will ask your calculator to compute 9**(9**9)), you need to run it in another process. This is the only easy way to sufficiently isolate it. Running it in your event system or even a different thread will not be enough. It is also possible to break things up into little chunks similar to the other solution, but requires very careful handling and usually isn't worth it; in any event, that doesn't allow you to do the same exact thing as just running the Python code.

这篇关于在Python中使用超时运行某些代码的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆