Adr*_*ter 7 multithreading arguments parameter-passing python-3.x
我在 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()
Run Code Online (Sandbox Code Playgroud)
threading.Thread问题在于,在调用and/or函数的过程中start,参数正在丢失其列表特征 ( isinstance(q_data.data, str)=False),但在scr_runner接受script_to_run_data参数的函数内部,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()
Run Code Online (Sandbox Code Playgroud)
现在,奇怪的是,当我让 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()
Run Code Online (Sandbox Code Playgroud)
产生错误:
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
Run Code Online (Sandbox Code Playgroud)
Sha*_*ger 10
args是要传递的参数序列;如果你想传递 alist作为唯一的位置参数,你需要传递args=(my_list,)它使其成为一个包含list(或者基本上等效地,args=[my_list])的一元组。
它需要是一系列参数,即使只传递一个参数,也是为了避免您创建的歧义。如果scr_runner采用三个参数,其中两个具有默认值,并且my_list长度为 3,那么您是否打算将三个元素作为三个参数传递,或者应该my_list作为第一个参数,而其他两个保留默认值?
| 归档时间: |
|
| 查看次数: |
30895 次 |
| 最近记录: |