【问题标题】:Passing arguments to threading.Thread将参数传递给 threading.Thread
【发布时间】:2018-08-13 16:22:57
【问题描述】:

我在 Windows 上使用 Python 3。我正在使用threading.Thread 动态运行一个函数,我可以带或不带参数调用它。我正在设置一个事物列表,其中的第一项是定义路径的字符串。其他参数将是列表中稍后的内容。所以,args 可能等于['C:\SomePath'] 或者它可能等于['C:\SomePath', 'First Argument', 'Second Argument']。我的电话是这样的:

my_script = threading.Thread(target=scr_runner, args=q_data.data)
my_script.start()

问题在于,在调用threading.Thread 和/或start 函数的过程中,参数正在失去其列表特征(isinstance(q_data.data, str)=False),但在scr_runner 函数内部,该函数采用@ 987654329@ 参数,isinstance(script_to_run_data, str)=True.

我需要这个参数在整个过程中保持一个列表。我该怎么做?

我在文档中读到 threading.Thread 函数需要一个元组。将['C:\SomePath'] 之类的内容转换为元组,然后变成字符串,是否存在问题?

提前感谢您的宝贵时间!

这是一个 MWE:

# coding=utf-8
""" This code tests conversion to list in dynamic calling. """

import threading


def scr_runner(script_to_run_data: tuple) -> None:
    """ This is the function to call dynamically. """
    is_list = not isinstance(script_to_run_data, str)
    print("scr_runner arguments are a list: T/F. " + str(is_list))


my_list=['C:\SomePath']
is_list = not isinstance(my_list, str)
print("About to run script with list argument: T/F. " + str(is_list))
my_script = threading.Thread(target=scr_runner, args=my_list)
my_script.start()

现在,奇怪的是当我让 my_list 有更多元素时出现错误:

# coding=utf-8
""" This code tests conversion to list in dynamic calling. """

import threading


def scr_runner(script_to_run_data: tuple) -> None:
    """ This is the function to call dynamically. """
    is_list = not isinstance(script_to_run_data, str)
    print("scr_runner arguments are a list: T/F. " + str(is_list))


my_list=['C:\SomePath', 'First Argument', 'Second Argument']
is_list = not isinstance(my_list, str)
print("About to run script with list argument: T/F. " + str(is_list))
my_script = threading.Thread(target=scr_runner, args=my_list)
my_script.start()

产生错误:

About to run script with list argument: T/F. True
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 916, in  
       _bootstrap_inner
    self.run()
  File "C:\ProgramData\Anaconda3\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
TypeError: scr_runner() takes 1 positional argument but 3 were given

【问题讨论】:

  • 上传带有函数定义的工作代码。
  • @Mehdi Sadeghi:你明白了!感谢您查看我的问题。
  • 可能有一个解决方案:将args=my_list 更改为args=[my_list],尽管我认为这种行为有点违反直觉。
  • @AdrianKeister:违反直觉?如果args 没有被隐式解包为target 的参数,您希望如何将两个或多个参数传递给线程?
  • @ShadowRanger:是的,这很好。谢谢!

标签: multithreading python-3.x arguments parameter-passing


【解决方案1】:

args 是要传递的参数序列;如果您想传入 list 作为唯一的位置参数,则需要传递 args=(my_list,) 以使其成为包含 list 的单元组(或大致等价的 args=[my_list])。

它必须是一系列参数,即使只传递了一个参数,也正是为了避免您创建的歧义。如果scr_runner 带三个参数,两个带默认值,my_list 的长度为 3,你的意思是把这三个元素作为三个参数传递,还是应该 my_list 作为第一个参数,另外两个保持默认?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-03
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2013-11-19
    相关资源
    最近更新 更多