我在 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
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()
现在,奇怪的是,当我让 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