How to terminate a Python script

前端 未结 10 1195
予麋鹿
予麋鹿 2020-11-22 04:34

I am aware of the die() command in PHP which exits a script early.

How can I do this in Python?

10条回答
  •  一整个雨季
    2020-11-22 04:59

    My two cents.

    Python 3.8.1, Windows 10, 64-bit.

    sys.exit() does not work directly for me.

    I have several nexted loops.

    First I declare a boolean variable, which I call immediateExit.

    So, in the beginning of the program code I write:

    immediateExit = False
    

    Then, starting from the most inner (nested) loop exception, I write:

                immediateExit = True
                sys.exit('CSV file corrupted 0.')
    

    Then I go into the immediate continuation of the outer loop, and before anything else being executed by the code, I write:

        if immediateExit:
            sys.exit('CSV file corrupted 1.')
    

    Depending on the complexity, sometimes the above statement needs to be repeated also in except sections, etc.

        if immediateExit:
            sys.exit('CSV file corrupted 1.5.')
    

    The custom message is for my personal debugging, as well, as the numbers are for the same purpose - to see where the script really exits.

    'CSV file corrupted 1.5.'
    

    In my particular case I am processing a CSV file, which I do not want the software to touch, if the software detects it is corrupted. Therefore for me it is very important to exit the whole Python script immediately after detecting the possible corruption.

    And following the gradual sys.exit-ing from all the loops I manage to do it.

    Full code: (some changes were needed because it is proprietory code for internal tasks):

    immediateExit = False
    start_date = '1994.01.01'
    end_date = '1994.01.04'
    resumedDate = end_date
    
    
    end_date_in_working_days = False
    while not end_date_in_working_days:
        try:
            end_day_position = working_days.index(end_date)
    
            end_date_in_working_days = True
        except ValueError: # try statement from end_date in workdays check
            print(current_date_and_time())
            end_date = input('>> {} is not in the list of working days. Change the date (YYYY.MM.DD): '.format(end_date))
            print('New end date: ', end_date, '\n')
            continue
    
    
        csv_filename = 'test.csv'
        csv_headers = 'date,rate,brand\n' # not real headers, this is just for example
        try:
            with open(csv_filename, 'r') as file:
                print('***\nOld file {} found. Resuming the file by re-processing the last date lines.\nThey shall be deleted and re-processed.\n***\n'.format(csv_filename))
                last_line = file.readlines()[-1]
                start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
                resumedDate = start_date
    
                if last_line == csv_headers:
                    pass
                elif start_date not in working_days:
                    print('***\n\n{} file might be corrupted. Erase or edit the file to continue.\n***'.format(csv_filename))
                    immediateExit = True
                    sys.exit('CSV file corrupted 0.')
                else:
                    start_date = last_line.split(',')[0] # assigning the start date to be the last like date.
                    print('\nLast date:', start_date)
                    file.seek(0) # setting the cursor at the beginnning of the file
                    lines = file.readlines() # reading the file contents into a list
                    count = 0 # nr. of lines with last date
                    for line in lines: #cycling through the lines of the file
                        if line.split(',')[0] == start_date: # cycle for counting the lines with last date in it.
                            count = count + 1
            if immediateExit:
                sys.exit('CSV file corrupted 1.')
            for iter in range(count): # removing the lines with last date
                lines.pop()
            print('\n{} lines removed from date: {} in {} file'.format(count, start_date, csv_filename))
    
    
    
            if immediateExit:
                sys.exit('CSV file corrupted 1.2.')
            with open(csv_filename, 'w') as file:
                print('\nFile', csv_filename, 'open for writing')
                file.writelines(lines)
    
                print('\nRemoving', count, 'lines from', csv_filename)
    
            fileExists = True
    
        except:
            if immediateExit:
                sys.exit('CSV file corrupted 1.5.')
            with open(csv_filename, 'w') as file:
                file.write(csv_headers)
                fileExists = False
        if immediateExit:
            sys.exit('CSV file corrupted 2.')
    
    

提交回复
热议问题