Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python threads - number of arguments Error

I am executing a command in a thread for almost 25k times like

if threaded is True:
                thread = Thread(target=threadedCommand, args=(cmd))
                thread.start()
                thread.join()  

def threadedCommand(command):
    if command is None:
        print 'can\'t execute threaded command'
        sys.exit(-1)
    print 'executing - %s'%(command)
    os.system(command)  

and command is like

cp file dir

and what I see is

Traceback (most recent call last): File "/usr/lib64/python2.6/threading.py", line 525, in __bootstrap_inner self.run() File "/usr/lib64/python2.6/threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) TypeError: threadedCommand() takes exactly 1 argument (52 given)

^CException in thread Thread-9377: Traceback (most recent call last): File "/usr/lib64/python2.6/threading.py", line 525, in __bootstrap_inner self.run() File "/usr/lib64/python2.6/threading.py", line 477, in run self.__target(*self.__args, **self.__kwargs) TypeError: threadedCommand() takes exactly 1 argument (56 given)

like image 297
daydreamer Avatar asked Sep 12 '11 19:09

daydreamer


People also ask

How many threads Python can handle?

Generally, Python only uses one thread to execute the set of written statements. This means that in python only one thread will be executed at a time.

How do you pass an argument to a thread in Python?

Example 1 - Thread Argument Passing long taskids[NUM_THREADS]; for(t=0; t<NUM_THREADS; t++) { taskids[t] = t; printf("Creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *) taskids[t]); ... } See the source code.

Can Python use multiple threads?

To recap, threading in Python allows multiple threads to be created within a single process, but due to GIL, none of them will ever run at the exact same time. Threading is still a very good option when it comes to running multiple I/O bound tasks concurrently.

How does ThreadPoolExecutor work Python?

ThreadPoolExecutor. ThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously. An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously. All threads enqueued to ThreadPoolExecutor will be joined before the interpreter can exit.


1 Answers

args must be a tuple. (cmd) is the same as cmd; you want a one-element tuple instead:

thread = Thread(target=threadedCommand, args=(cmd,))
#                                                ^
like image 74
phihag Avatar answered Oct 21 '22 03:10

phihag