将字符串作为arg传递到Python的threading.Thread中

时间:2019-03-27 00:48:43

标签: python multithreading

我试图弄清楚如何在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

1 个答案:

答案 0 :(得分:0)

您可以继承Thread,并将my_func定义为run方法,并创建一个新实例。

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()