简体   繁体   English

如何在 If 语句中退出/中断 Python 自动化脚本(不在循环内)

[英]How to Exit/Break Python Automation Script in If Statement (Not inside a loop)

I am trying to run a program but that program needs to read a config file.我正在尝试运行一个程序,但该程序需要读取配置文件。 This config file has to have a base directory from which it will read the files.此配置文件必须有一个基本目录,它将从中读取文件。 The config file has several sections for different sub directories from the base file.配置文件有几个部分,用于与基本文件不同的子目录。

Ultimately I want the program to break the script and return an error message if the base directory is not inside the config file.最终,如果基本目录不在配置文件中,我希望程序中断脚本并返回错误消息。

This requires an If Statement.这需要一个 If 语句。 However if statements typically don't break scripts.但是 if 语句通常不会破坏脚本。 How can I write an if statemtent that will break the function in which this config file is read from which will also break the script?如何编写一个 if 语句来破坏 function 从中读取此配置文件的同时也会破坏脚本? This function will be used inside another function这个 function 将在另一个 function 内部使用

def process_dirconfig_file(config_file_from_sysarg):
    config = ConfigParser()
    config.read(config_file_from_sysarg)
    dirconfig_file_Pobj = Path(config_file_from_sysarg)
    if Path.is_file(dirconfig_file_Pobj):
        parseddict = {}
        for sect in config.sections():
            for k, v in config.items(sect):
                # print('{} = {}'.format(k, v))
                parseddict[k] = v
        print(parseddict)
        if ("base_dir" not in parseddict) or (parseddict["base_dir"] == ""):
            print(f"{Fore.RED} Error: Your config file is missing 'base directory' for file processing")
        elif("archive_dir" not in parseddict) or (parseddict["archive_dir"] == ""):
            print(f"{Fore.RED} Error: Your config file is missing 'archive directory' for file processing")
        elif ("error_dir" not in parseddict) or (parseddict["error_dir"] == ""):
            print(f"{Fore.RED} Error: Your config file is missing 'error directory' for file processing")
        elif ("empty_dir" not in parseddict) or (parseddict["empty_dir"] == ""):
            print(f"{Fore.RED} Error: Your config file is missing 'empty directory' for file processing")
    else:
        print(f"{Fore.RED} Error: No directory config file. Please create a config file of directories to be used in processing")

This function is being used inside this function:此 function 正在此 function 内部使用:

def odf_history_from_csv_to_dbtable(csvfile_path_list, db_instance):
    odfsdict = db_instance['odfs_tester_history']
    #table_row = {}
    totalresult_list = []
    process_dirconfig_file(dirconfig_file)
    for csv in csvfile_path_list:  # is there a faster way to compare the list of files in archive and history?
        if csv not in archivefiles_path_set:
            csvhistoryfilelist_to_dbtable(csv, db_instance)
            odfscsv_df = pd.read_csv(csv, header=None, names=['ODFS_LOG_FILENAME', 'ODFS_FILE_CREATE_DATETIME', 'LOT', 'TESTER', 'WAFER_SCRIBE'])
            odfscsv_df['CSV_FILENAME'] = csv.name #add csvfilename column to existing df
            result = odfscsv_df.to_sql('odfs_tester_history', con=odfsdict['engine'], if_exists='append', index=False)
            totalresult_list.append(result)


        else:
            print(csv.name + " is in archive folder already")
    #print (totalresult_list)
    return totalresult_list

db_instance = dbhandler()
odfs_tabletest_dict = db_instance['odfs_tester_history_files']

You can use a structure like this: (Basic Exception Handling) :您可以使用这样的结构:(基本异常处理)

In case there are two methods: Caller(b) and Called(a)如果有两种方法:Caller(b) 和 Called(a)

def a(x):
try:
    if(x%2==0): raise Exception("Even Integer")
    else: raise Exception("Odd Integer")
except Exception as e:
    raise Exception(e)


def b():
    try:
        a(3)
    except Exception as e:
        print(e)
        
b()

Answer:回答:

Odd Integer

If I understand your question correctly it sounds like you should be using try/except instead of if statements.如果我正确理解您的问题,听起来您应该使用 try/except 而不是 if 语句。 This will try to read the code except when it comes to an error in which case it will stop the code and return that error.这将尝试读取代码,除非遇到错误,在这种情况下它将停止代码并返回该错误。

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

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