如何在指定时间内终止功能

时间:2019-01-26 10:44:35

标签: python python-imaging-library

我有一个确定图像是否头像的功能。一旦执行时间超过5秒,我就需要终止被调用的函数。

#!/usr/bin/python
from PIL import Image
from urllib.request import urlopen


def avatar_detect(image_url):
    img = Image.open(urlopen(image_url))
    total = 0
    pixels = img.convert('RGBA').load()
    width, height = img.size
    colours = list()
    for x in range(width):
        for y in range(height):
            r, g, b, _ = pixels[x, y]
            hex_ = '#{:02x}{:02x}{:02x}'.format(r, g, b)
            colours.append(hex_)
            total += 1
        total += 1
    highest = colours.count(max(set(colours), key=colours.count))
    return True if highest / total > 0.5 else False


# https://peopledotcom.files.wordpress.com/2018/10/the-weeknd-1.jpg
# -> should be terminated after 5 seconds

# https://avatars2.githubusercontent.com/u/8427649?s=64&v=4
# -> fast execution less than 5 seconds

url = 'https://avatars2.githubusercontent.com/u/8427649?s=64&v=4'
print(avatar_detect(url))

1 个答案:

答案 0 :(得分:1)

您可以创建一个进程,并在等待5秒钟后将其保持活动状态将其终止。以下代码可以进入主要功能:

p = Process(target = avatar_detect, args = ('image_url',))
p.start()    
p.join(5)    
if p.is_alive():
    print('Time-out occurred')
    p.terminate()
    p.join()

别忘了导入Process

from multiprocessing import Process