python theading.Timer:如何将参数传递给回调?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4415672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:40:11  来源:igfitidea点击:

python theading.Timer: how to pass argument to the callback?

pythontimer

提问by Bin Chen

My code:

我的代码:

    import threading

def hello(arg, kargs):
    print arg

t = threading.Timer(2, hello, "bb")
t.start()

while 1:
    pass

The print out put is just:

打印出来的只是:

b

How can I pass a argument to the callback? What does the kargs mean?

如何将参数传递给回调?kargs 是什么意思?

采纳答案by Glenn Maynard

Timertakes an array of arguments and a dict of keyword arguments, so you need to pass an array:

Timer需要一个参数数组和一个关键字参数字典,所以你需要传递一个数组:

import threading

def hello(arg):
    print arg

t = threading.Timer(2, hello, ["bb"])
t.start()

while 1:
    pass

You're seeing "b" because you're not giving it an array, so it treats "bb"an an iterable; it's essentially as if you gave it ["b", "b"].

你看到“b”是因为你没有给它一个数组,所以它对待"bb"一个可迭代的;它本质上就好像你给了它一样["b", "b"]

kwargsis for keyword arguments, eg:

kwargs用于关键字参数,例如:

t = threading.Timer(2, hello, ["bb"], {arg: 1})

See http://docs.python.org/release/1.5.1p1/tut/keywordArgs.htmlfor information about keyword arguments.

有关关键字参数的信息,请参阅http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html

回答by outis

The third argument to Timeris a sequence. Since you pass "bb" as that sequence, hellogets the elements of that sequence ("b" and "b") as separate arguments (argand kargs). Put "bb" in a list and hellowill get the string as the first argument.

的第三个参数Timer是一个序列。由于您将“bb”作为该序列传递,因此将该序列hello的元素(“b”和“b”)作为单独的参数(argkargs)获取。将“bb”放入列表中,hello并将获得字符串作为第一个参数。

t = threading.Timer(2, hello, ["bb"])

As for hello's parameters, you probably mean:

至于hello的参数,您可能的意思是:

def hello(*args, **kwargs):

The meaning of **kwargsis covered in the queston "What does *args and **kwargs mean?"

的含义**kwargs包含在问题“ *args 和 **kwargs 是什么意思?