0

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. However if statements typically don't break scripts. 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? This function will be used inside another 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:

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']
14
  • Since it is a function you can simply return. Commented Jun 29, 2020 at 17:28
  • Ah ok. WHat if it's not a function? @KlausD. Commented Jun 29, 2020 at 17:28
  • This function is going to be used within a function @KlausD. How about that situation. I want this function to break through all the functions and exit the script Commented Jun 29, 2020 at 17:29
  • 1
    You can use exception handling. and throw an exception in such cases which prevents the flow to move forward. Commented Jun 29, 2020 at 17:30
  • 1
    Well, you should make sure your question contains all the information for an answer. A sequence of "but if..." additions will not increase clarity. Commented Jun 29, 2020 at 17:33

2 Answers 2

1

You can use a structure like this: (Basic Exception Handling) :

In case there are two methods: Caller(b) and 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
Sign up to request clarification or add additional context in comments.

5 Comments

So here the exception from a triggers the try on b which makes it print the except divide by 0? What if def a has multiple exceptions? How would be know which one to throw? @Sanket Singh
you can raise a particular error for that in if else condition in try block of "a" and then catch that exception as "e" and pass that "e" to calling method "b" and can print there. Edited my answer. Hope this will help.
I see I'll play around with that. Thanks!
I hope this solution helped you with your query. You can accept and upvote if it did @edo101
Yeop marked as ansewer and upvoted. This exactly wha I am looking for, especially with your edits @Sanket Singh
0

If I understand your question correctly it sounds like you should be using try/except instead of if statements. 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.

1 Comment

This function will be inside another function. If it returns an exception, it won't necesarly break the code @Jonathan Shelton

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.