简体   繁体   中英

Python issue with threading.timer/for loop

been going around in circles on this code for a while and could use a hand. it's probably something small i missed somewhere.

i have a CSV file that im trying to pry some values out of, for our purposes it looks like this:

columns : A, B, C, D
row[0]: bad, x, y, s
row[1]: good1, x, y, z
row[2]: good2, x, y, z

Section of my Code looks like this:

def match_file():
    global name,
    aziVal1 = 'z'
    with open(path_address, 'rb') as userdataCSV:
        reader = csv.reader(userdataCSV)
        for row in reader:
            for (i,v) in enumerate(row):
                if aziVal1 in row:  
                    columns[i].append(v)
        name = columns[0]
        print name
    return 

If i run this code one at a time from terminal , it works fine and gives an output of

['good1', 'good2']

but when i try to automate this with threading.Timer,

def altogether():
    threading.Timer(3.0, altogether).start()
    match_file()
    return 

this becomes the output

['good1', 'good2']
['good1', 'good2', 'good1', 'good2']
['good1', 'good2', 'good1', 'good2', 'good1', 'good2']
['good1', 'good2', 'good1', 'good2', 'good1', 'good2', 'good1', 'good2']

I really don't know what's wrong with it. I've tried deleting the global variables but i need that for another function, also tried shifting around the indentations to no avail. Could really use a hand around here. Thanks!

Try to reset columns in the beginning of every loop.

def match_file():
    global name,
    aziVal1 = 'z'
    columns = []
    with open(path_address, 'rb') as userdataCSV:
        reader = csv.reader(userdataCSV)
        for row in reader:
            for (i,v) in enumerate(row):
                if aziVal1 in row:  
                    columns[i].append(v)
        name = columns[0]
        print name
    return

I think it's beacause of this:

def altogether():
    threading.Timer(3.0, altogether).start() # You're passing this same methode into the timer.
    match_file()
    return 

With toher words, when you call the methode altogether. You start a Timer, which also starts this method, which starts a new Timer. Etc. You should do this:

def altogether():
    threading.Timer(3.0, match_file).start() # Passing match_file into the timer
    return 

OR:

threading.Timer(3.0, altogether).start() # Initialize outside the methode.
def altogether():
    match_file()
    return

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM