Sie sind auf Seite 1von 5

12

Contributors
13
Replies
33
Views
3 Years
Discussion Span
1 Year Ago
Last Updated by nytman
JOIN DANIWEB LOG IN 1,105,473 COMMUNITY MEMBERS
Software Development > Python > Tutorials >
SIMPLE threading tutorial
Ad: DaniPad by DaniWeb coworking community in Queens, NYC
AutoPython
4 Years Ago
!USING PYTHON 3.1!
Hello DaniWeb! Today I'm going to be posting a simple threading tutorial. First of all, what is
threading? Well, threading is just another way of doing a side task without interrupting the main
program. Now here's a simple example. Let's say we are going to make a simple program. When
the program starts it is going to start a timer, and it will show the time. Now, observe these 2,
similar programs.
Good version:
1. import threading
2. import time
3.
4. threadBreak = False
5. def TimeProcess():
6. while not threadBreak:
7. print (time.time() - startTime)
8.
9. startTime = time.time()
10.
11. threading.Thread(target = TimeProcess).start()
12.
13. input()
14. threadBreak = True
15. quit()
Bad Version:
1. import threading
2. import time
3.
4. threadBreak = False
5. def TimeProcess():
6. while not threadBreak:
7. print (time.time() - startTime)
8.
9. startTime = time.time()
10.
11. TimeProcess()
12.
13. input()
14. threadBreak = True
15. quit()
Now, you may notice that, the working version will exit after you press any key. The not working
version, will not let you quit after pressing anything. That is because this command:
threading.Thread(target = FunctionName)
Will run that function, but the function won't take control over the main code. Okay, now I have
some more explaining to do. Let's view the commented version of the code:
1. import threading
2. import time
3.
4. threadBreak = False
5. def TimeProcess():
6. while not threadBreak: ## it will run this as long as threadBreak is false


3
Search
It's free to join us and begin learning, sharing knowledge, and engaging with other developers and IT professionals
DaniWeb IT Discussion Community
7. print (time.time() - startTime)
8.
9. startTime = time.time() ## I'm not sure how this works, just learned the trick.
10.
11. threading.Thread(target = TimeProcess).start() ## Starts the thread in the background.
12.
13. input()
14. threadBreak = True ## stops the thread
15. quit()
That's a simple form of threading. But here's a more functional version of the above program.
1. import threading
2. import time
3.
4. print ("Press any key to start timer!")
5. input()
6.
7. threadBreak = False
8. def TimeProcess():
9. while not threadBreak:
10. print (time.time() - startTime)
11.
12. startTime = time.time()
13.
14. threading.Thread(target = TimeProcess).start()
15.
16. input()
17. threadBreak = True
18. input ()
19. quit()
Well that's a simple threading tutorial! Threading can have many more uses, and don't only limit
yourself to this.
Paul Thompson
Veteran Poster
1,095 posts
since May 2008

0 4 Years Ago
Ah, excellent. threading is a great thing to show people.... Im still stuck for another idea for a
tutorial though.. Unless i do wxPython ones. I already have some of those at my site tho :P

AutoPython
Junior Poster
142 posts
since Sep 2009

0 4 Years Ago
Yeah, I just can't stand it seeing only 3 tutorials for such a great language. I want this place
to be a significant source for tutorials.

soldner
Newbie Poster
2 posts
since Oct 2009

0 4 Years Ago
Thanks for the threading, it is easier to understand when you see it. For more tutorials, how
about the web? I'm using a php script in my wife's blog and would like to use Python.
What I don't know is:
How the php program is executed (how to execute the Python)
Where to variable mc_user_ip comes from, I think it is a return for the php program,
How do I see the return values,
How does the web pages's values get passed to the php program.
I've found some Python examples of getting the ip address, but the rest of it I haven't found.
<head>
<script src='http://code.vietwebguide.com/php/addr.php' type='text/javascript'></script>
<script type='text/javascript'>
//<!CDATA[
// Banned isps
var banned_ip = new Array();
banned_ip[0] = '72.129.151.108':
var mes_bi = "Kein Anschluss an diesen Nummer.";
for(var i=0;i<banned_ip.length;i++) {
eval('var re = /^' + banned_ip + '/ ;');
if (re.test(mc_user_ip))

{
document.write('<style type="text/css">');
document.write('BODY{display:none;}');
document.write('<\/style>');
alert(mes_bi);
break;
}
}
//]]>
</script>
AutoPython
Junior Poster
142 posts
since Sep 2009

0 4 Years Ago
Hm, I am not familiar of using Python in the web. Try making a new thread on this and you'll
probably get more help.

Leyond
Newbie Poster
1 post
since May 2010

0 3 Years Ago
Great tutorial, it is helpful..
albruno
Newbie Poster
2 posts
since May 2009

0 3 Years Ago
for python
i believe that you need to execute it (if windows) through the cmd window
hope that this helps
Thanks for the threading, it is easier to understand when you see it. For more tutorials, how
about the web? I'm using a php script in my wife's blog and would like to use Python.
What I don't knowis:
Howthe php program is executed (howto execute the Python)
Where to variable mc_user_ip comes from, I think it is a return for the php program,
Howdo I see the return values,
Howdoes the web pages's values get passed to the php program.
I've found some Python examples of getting the ip address, but the rest of it I haven't found.
<head>
<script src='http://code.vietwebguide.com/php/addr.php' type='text/javascript'></script>
<script type='text/javascript'>
//<!CDATA[
// Banned isps
var banned_ip = newArray();
banned_ip[0] = '72.129.151.108':
var mes_bi = "Kein Anschluss an diesen Nummer.";
for(var i=0;i<banned_ip.length;i++) {
eval('var re = /^' + banned_ip + '/ ;');
if (re.test(mc_user_ip))
{
document.write('<style type="text/css">');
document.write('BODY{display:none;}');
document.write('<\/style>');
alert(mes_bi);
break;
}
}
//]]>
</script>

marshrobin1
Newbie Poster
1 post
since Jul 2010

0 3 Years Ago
Excellent. Threading is a great thing to show people....thanks
Robin marsh:)

pyTony
pyMod
6,103 posts
since Apr 2010
Moderator
Featured



1 3 Years Ago
Here is little modified version to be more evident what it does:
1. ## run with Python 3 from command line or double click
2. import threading
3. import time
4.
5. def TimeProcess():
6. while not threadBreak:
7. print (time.time() - startTime)
8.
9. input("""
10. Press enter key to start timer,

View similar articles that have also been tagged: python simple threading tutorial
ajax applescript beginner binary blogs browser c# c++ calculator cgi class classes code collection collision convert csv designer dictionary django
Software Development > Python
11. after some time push enter again to stop it!""")
12.
13. threadBreak = False
14.
15. startTime = time.time()
16.
17. threading.Thread(target = TimeProcess).start()
18.
19. input()
20. threadBreak = True
21. input ('Quit by enter')
22. quit()
woooee
Posting Maven
2,798 posts
since Dec 2006


2 3 Years Ago
Does everyone know about Doug Hellmann's Python Module Of The Week. A good source
for basic learning.
http://www.doughellmann.com/PyMOTW/threading/index.html#module-threading
http://www.doughellmann.com/PyMOTW/about.html

seanbp
Junior Poster
129 posts
since Jul 2010

0 3 Years Ago
1. startTime = time.time() ## I'm not sure how this works, just learned
the trick.
This line gets the current system time (a form which doesn't reset to zero). The script
calculates the difference between the program start time and the current time.

twohot
Newbie Poster
7 posts
since Dec 2010

0 3 Years Ago
That should fill the screen with a lot of time output .... shouldn't there be a sleep statement
somewhere to make it more dramatic?

richieking
Posting Shark
926 posts
since Jun 2009

0 3 Years Ago
I am thinking of writting a tut about threading and socket. ;)
nytman
Light Poster
25 posts
since Nov 2012

0 1 Year Ago
This thread is really nice, a good basics regarding thread, i was thinking to implement
thread with some practicle use, so is there is any place where i could find threads with
general examples where threads will do more than just printing time calculation .
Regards

You
Code Inline Code Link H1 H2

Post:
Submit your Reply (Alt+S)

Start New Discussion

Recently Updated Articles Recommended Join the DaniWeb Community Ad: DaniPad by DaniWeb coworking community in Queens, NYC
duplicate dynamic error error-handling file files flask for framework function functions glob google grading gui header help how-to html if import in input
java javascript jquery learning linear linux localhost loops math me microsoft module mongodb mongoengine multilingual mysql new newbie nltk outlook
php posting problem programming pygame pyramid python python3 rate regex run server simple spreadsheet sql sqlite3 storbinary text theory
timeout tkinter tutorial ui value variables virus web web.py win32com win8 windows windows-8 write wxpython xls xml xna
2014 DaniWeb LLC
Page generated in 0.1138 seconds using 2.86MB of memory
Home About Us Contact Us Advertising Vendors RSS Feed TOS Donate API Rules

Das könnte Ihnen auch gefallen