简体   繁体   English

如何在任意超时后停止Python程序

[英]How to stop a Python program after some arbitrary timeout

Just for instance, this code is working 例如,这段代码正在运行

import urllib

image = urllib.URLopener()
file_ = 1
name = 1
for i in range(1,1000):
    try:
        image.retrieve("http://mangawriter.com/pics/pic"+str(file_)+".jpeg","pic"+str(name)+".jpeg")
        print "save file %s" %file_ 
        name += 1
        file_ += 1
    except IOError:
        file_ += 1

How could I make it stop after some time was spent, even if the code is still being ran? 即使代码仍在运行,我怎么能在花费一些时间后停止它? Please, help me to figure it out. 请帮我解决一下。

I would use the multiprocessing module, which generates new processes (not threads) for parallelizing tasks. 我会使用multiprocessing模块,它生成用于并行化任务的新进程(而不是线程)。

How to do it? 怎么做? First, the actual download code should be put in a function: 首先,实际的下载代码应该放在一个函数中:

import urllib
import multiprocessing
import time

def download_images():
    image = urllib.URLopener()
    file_ = 1
    name = 1
    for i in range(1,1000):
        try:
            image.retrieve("http://mangawriter.com/pics/pic"+str(file_)+".jpeg","pic"+str(name)+".jpeg")
            print "save file %s" %file_ 
            name += 1
            file_ += 1
        except IOError:
            file_ += 1

Now, we create a new multiprocessing.Process object, passing the function above as its target. 现在,我们创建一个新的multiprocessing.Process对象,将上面的函数作为目标传递。 This object will start a process just to execute this function: 该对象将启动一个进程来执行此函数:

downloader = multiprocessing.Process(target=download_images)

Once we have created the process object, just call its start() method. 创建过程对象后,只需调用其start()方法即可。 This will start a process that will run in parallel: 这将启动一个并行运行的进程:

downloader.start()

Since it is running in parallel, the main program keeps executing. 由于它是并行运行的,因此主程序继续执行。 Now, we define a timeout and sleep for the time of this timeout. 现在,我们在此超时时间定义超时和休眠。 In the example below, the timeout is 15 seconds: 在下面的示例中,超时为15秒:

timeout = 15
time.sleep(timeout)

Once the timeout ends, just terminate the downloader process: 超时结束后,只需终止下载程序:

downloader.terminate()

The full program can be found here . 完整的程序可以在这里找到。

This one really works for me and it is very simple. 这个对我很有用,而且非常简单。 Suppose that we want stop after 25 seconds. 假设我们想要在25秒后停止。

    import timeit #we will need the command default_timer() that checks the actual time
    start = timeit.default_timer()
    while timeit.default_timer()-start<=25:
         "you code here"

Not the best but a usable way: 不是最好的,但可用的方式:

You can spawn a child thread using threading module to do this, and, set an time.sleep in your main thread, so when time is out, you can kill the child thread. 您可以使用threading模块生成子线程来执行此操作,并在主线程中设置time.sleep,因此当时间结束时,您可以终止子线程。

EDIT : just something like this: 编辑 :就像这样:

import threading
import urllib

def child(file_, name):
    try:
        image = urllib.URLopener()
        image.retrieve("http://mangawriter.com/pics/pic"+str(file_)+".jpeg","pic"+str(name)+".jpeg")
        print "save file %s" % file_
    except IOError:
        pass

file_ = 1
name = 1
for i in range(1,1000):
    t = threading.Thread(target = child, args = (file_, name))
    t.daemon = True
    t.start()
    t.join(timeout = 10)
    file_ += 1
    name += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM