繁体   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