简体   繁体   English

Python的threading.timer / for循环问题

[英]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: 我有一个CSV文件,我试图从中撬出一些值,出于我们的目的,它看起来像这样:

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, 但是当我尝试使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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