【问题标题】:Why is this sending so many variables?为什么这会发送这么多变量?
【发布时间】:2011-05-21 03:25:49
【问题描述】:

我创建了一个函数timeout_func,它将正常运行另一个函数并返回其输出,但如果函数超过“秒”,它将返回一个字符串“失败”。 基本上,这是一种使可以无限运行的函数超时的解决方法。 (Windows 上的 python 2.7)(为什么我需要一个解决方法,为什么我不能让函数成为非无限的?因为有时你不能这样做,它在已知的称为 bugs进程即:fd = os.open('/dev/ttyS0', os.O_RDWR)

无论如何,我的 timeout_func 的灵感来自我在这里收到的帮助: kill a function after a certain time in windows

我的代码的问题在于,由于某种原因,do_this 函数正在接收 14 个变量而不是 1 个。通过双击脚本或从 python.exe 运行它时,我收到错误消息。从 IDLE 中,您不会收到任何异常错误....

但是,如果我将其更改为:

def do_this(bob, jim):
return bob, jim

效果很好……

这里发生了什么?它不喜欢 1 变量函数...?

import multiprocessing
import Queue


def wrapper(queue, func, func_args_tuple):
    result = func(*func_args_tuple)
    queue.put(result)
    queue.close()

def timeout_func(secs, func, func_args_tuple):
    queue = multiprocessing.Queue(1) # Maximum size is 1
    proc = multiprocessing.Process( target=wrapper, args=(queue, func, func_args_tuple) )
    proc.start()

    # Wait for TIMEOUT seconds
    try:
        result = queue.get(True, secs)
    except Queue.Empty:
        # Deal with lack of data somehow
        result = 'FAILED'
        print func_args_tuple
    finally:
        proc.terminate()

    return result


def do_this(bob):
    return bob

if __name__ == "__main__":
    print timeout_func( 10, do_this, ('i was returned') )
    x = raw_input('done')

【问题讨论】:

    标签: python


    【解决方案1】:

    ('i was returned') 不是元组。它计算为一个字符串,就像 (3+2) 计算为一个整数一样......

    调用 do_this(*('i was returned')) 将序列 'i was returned' 的每个字母作为单独的参数传递 - 相当于:

    do_this('i', ' ', 'w', 'a', 's', ' ', 'r', 'e', 't', 'u', 'r', 'n', 'e', 'd')
    

    使用('i was returned',) 强制它成为一个元组(由于尾随逗号)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 2016-06-14
      • 2012-11-18
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多