0

I'm importing multiple python threads from different directories and then want to run them simultaneously.

Here's my parent:

import sys
import thread

sys.path.append('/python/loanrates/test')

import test2

thread.start_new_thread(test2.main())

and here's one of my child's:

import json 

def main():

    data = 'ello world'

    print data 

    with open( 'D:/python/loanrates/test/it_worked.json', 'w') as f:
        json.dump(data, f)

if __name__ == '__main__':
    main() 

but I am getting this error:

TypeError: start_new_thread expected at least 2 arguments, got 1

What is a simple way I can get this thread started (and then sequentially run multiple threads using the same method)

1
  • David if my answer has solved your question please consider accepting it Commented Feb 22, 2016 at 14:47

1 Answer 1

1

You also need to provide a tuple with the argument to run the function with. If you have none, pass an empty tuple.

thread.start_new_thread(test2.main, ())

From the docs of thread.start_new_thread(function, args[, kwargs]) (boldface mine):

Start a new thread and return its identifier. The thread executes the function function with the argument list args (which must be a tuple). The optional kwargs argument specifies a dictionary of keyword arguments. When the function returns, the thread silently exits. When the function terminates with an unhandled exception, a stack trace is printed and then the thread exits (but other threads continue to run).

You can also:

thread = Thread(target = test2.main, args, kwargs)

thread.start() // starts the thread

thread.join() // wait

Read more on this approach to creating and working with threads here.

Sign up to request clarification or add additional context in comments.

8 Comments

I get invalid syntax from using this: thread.start_new_thread(test2.main, ( , ) )
Also using thread = Thread(target = test2.main, args, kwargs) i get Thread is not defined
"Thread is not defined" -> import the library (stackoverflow.com/questions/28873479/…). I am checking regarding the syntax error now
Check it now (removed the comma , )
Thanks, however Is still get this error Unhandled exception in thread started by sys.excepthook is missing lost sys.stderr
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.