[Tutor] how to make a script do two things at once.

Kent Johnson kent37 at tds.net
Mon Aug 22 04:45:33 CEST 2005

nephish wrote:
> Hey there,
> i have a simple question about getting a script to do
> two things at once.
> like this.
> for i in range(100):
>     print i
>     time.sleep(.2)
>     if i == 15:
>         os.system('python /home/me/ipupdate.py')
> print 'done'
> when i run this, it stops at 15 and runs the script called out in the 
> os.system line. i know it is supposed to do that. But, how could i get a 
> script to do this without stopping the count (or delaying it unill the 
> script called exits) 

One way to get a script to do two things 'at once' is to use threads. Threads are also a good way to introduce strange bugs into your program so you should do some reading about them. I can't find a good introduction - anyone else have a suggestion? Here is a brief one:

Here are a couple of articles, not really introductory:

Anyway here is something to get you started, this version of your program starts a new thread to do the os.system call, that way the main thread doesn't block.

import os, threading, time

def doSomething():
    ''' This function will be called from the second thread '''
    os.system('''python -c "from time import sleep;sleep(2);print 'hello'"''')
for i in range(30):
    print i
    if i == 10:
        print 'Starting thread'
print 'done'


More information about the Tutor mailing list