我正在尝试弄清楚如何在Python threading.Thread
中将字符串作为参数传递。以前遇到过此问题:Python Threading String Arguments
有没有更好的传递字符串的方法?肯定有更明显的方法,而我对编程太陌生了,搞不懂。
代码块A
import threading
def start_my_thread():
my_thread = threading.Thread(target=my_func, args="string")
my_thread.start()
def my_func(input):
print(input)
结果:TypeError: my_func() takes 1 positional argument but 6 were given
代码块B
import threading
def start_my_thread():
my_thread = threading.Thread(target=my_func, args=("string",))
my_thread.start()
def my_func(input):
print(input)
结果:string
发布于 2019-03-27 09:01:31
您可以继承线程,并在run method.and创建新实例时定义my_func。
import threading
class MyThread(threading.Thread):
def __init__(self,string):
super().__init__()
self.string = string
def run(self):
print(self.string)
# def start_my_thread():
# my_thread = threading.Thread(target=my_func, args=("string",))
# my_thread.start()
# def my_func(input):
# print(input)
if __name__ == "__main__":
MyThread("hello").start()
https://stackoverflow.com/questions/55368199
复制相似问题