gpt4 book ai didi

multithreading - 将参数传递给 threading.Thread

转载 作者:行者123 更新时间:2023-12-03 12:45:30 27 4
gpt4 key购买 nike

我在 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 内函数,它采用 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

最佳答案

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

它需要是一系列参数,即使只传递一个参数,也正是为了避免您创建的歧义。如 scr_runner接受三个参数,其中两个具有默认值,以及 my_list长度为 3,您的意思是将三个元素作为三个参数传递,还是应该 my_list是第一个参数,其他两个保持默认?

关于multithreading - 将参数传递给 threading.Thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49120190/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com