簡體   English   中英

使用Python退出嵌套函數

[英]Exit nested function with Python

我正在編寫一個Python腳本來讀取一個文本文件,該文件每小時更新一次,從中刪除一些數據,然后寫入csv文件。 我可以將數據進行整理並寫入csv沒問題。 我正在嘗試實現每天創建一個新的csv文件的功能,以便使文件足夠小以方便人類閱讀並允許輕松搜索過去的數據。我還想用日期命名該csv。 再次,那部分工作。 我的腳本讀取文本文件的時間戳,並將其解析為字符串。 我還將解析后的時間字符串保存到文本文件中,以便進行比較。 我的問題是,即使日期相同且時間相同,我的腳本仍會將相同的數據寫入csv,而不是退出腳本,直到下一次在cron下運行。 我認為問題所在的行是第16行。我認為這是問題所在,因為當比較兩個字符串時,它應該發現它們是相同的,並且腳本應該退出。 但是,它不會這樣做,並且仍會繼續編寫腳本。 這可能不是問題,真正的問題可能在其他地方,但是我沒有足夠的經驗來找到缺陷。 我已經研究了這個問題一個多星期,並嘗試搜索我可能想到的每個可能的問題,但沒有一個解決了這個問題。 任何幫助將非常感激。 我認為我對所有內容的評論都足夠好,可以進行同行評審,如果需要更好地解釋,請告訴我。

def date_check(new_date, save_date): # checks if date is the same
    if new_date != save_date: # if dates are not the same the call new_csv to make new csv
        new_csv(new_date) # pass date string of new file for file name  
    if new_date == save_date: # if the dates are the same then call time check      
        time_check(new_time, save_time) # pass variables to compare

def time_check(new_time, save_time): # function to check if time is the same    
    if new_time != save_time: # if times are not same then parce the data
        parcer(time_string, data) # pass time_string and data string to be appended 
    if new_time == save_time: # if times are the same then(same file) exit program
        sys.exit() # exit program completely, THIS PART DOES NOT WORK

由於這是Google中“退出嵌套函數python”的第一搜索結果,因此標題中的問題的答案是:

使用sys.exit()例如

import sys

def foo():
    print("Loading bar")
    while(True):
        bar()

def bar():
    sys.exit()

def main():
    print("Loading foo")
    while(True):
        foo()

if __name__ == '__main__':
    main()

我以為OP自一年前開放以來就解決了他們的問題,如果有人堅持使用類似的東西,它看起來new_time永遠不會等於save_time,因此sys.exit()永遠不會得到評估。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM