Threading in Python, Please check the script
davea at davea.name
Wed Jan 14 11:40:27 CET 2015
On 01/14/2015 01:22 AM, Robert Clove wrote:
> Hi All,
In any new thread, you should specify what versions of Python and OS
you're using. I'll assume Python 2.7 and Linux for this message.
> I have made a script in which i have started two thread named thread 1 and
> thread 2.
> In thread 1 one function will run named func1 and in thread 2 function 2
> will run named func 2.
> Thread 1 will execute a command and wait for 60 seconds.
> Thread 2 will run only till thread 1 is running .
> Again after that the same process continues in while after a break of 80
> I am a beginner in python.
> Please suggest what all i have done wrong and how to correct it.
> import threading
> import time
> import subprocess
> import datetime
> import os
> import thread
> thread.start_new_thread( print_time, (None, None))
> thread.start_new_thread( print_time1, (None, None))
In these two lines you're referencing a function that hasn't been
defined yet. This top-level code should be moved to the end of the
file, after the if __name__ = "__main__": line
Or just drop it, since you've got a second set of code also trying to
create new threads.
> command= "strace -o /root/Desktop/a.txt -c ./server"
> final_dir = "/root/Desktop"
> exitflag = 0
> # Define a function for the thread
> def print_time(*args):
> print "IN first thread"
> proc = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,
You just set a local variable, not the global one. So it won't be
visible in the other thread. If you must rebind a top-level variable
from a function, you need to use the 'global' declaration in your function.
> def print_time1(*args):
> print "In second thread"
> global exitflag
> while exitflag:
> #proc =
> # Create two threads as follows
> while (1):
> z = t1.isAlive()
> z1 = t2.isAlive()
> if z:
> if z1:
What are you trying to do in those two lines? If nothing else, they'll
give an indentation error. But if you fix that, you'll still have the
potential problem of creating more and more threads as you loop around.
> print "In try"
Bare excepts are "evil." Your user can't tell what went wrong, from a
syntax error to the user hitting control-C. Even if you can't handle a
particular kind of exception, at least have the courtesy of telling the
user what went wrong.
> print "Error: unable to start thread"
I'm sure there are other things, but these popped out at me.
More information about the Python-list