0

I am trying to figure out how to pass a string as an argument in Python threading.Thread. This problem has been encountered before: Python Threading String Arguments

Is there a better way to pass in a string? There has to be a more obvious way, and I am just too new to coding to figure it out.

Code Block 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)

Result: TypeError: my_func() takes 1 positional argument but 6 were given

Code Block 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)

Result: string

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119

1 Answers1

0

you can inherit Thread,and define my_func as run method.and create a new instance.

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()
goudan
  • 58
  • 4