Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking if __name__ when a condition is not met

I am using

if __name__ == "__main__":

to run my defined functions.

However as an error catching measure I am trying to implement a way to ensure that file paths have been entered correctly into the .bat file my script is ran from, the file names are passed in as arguments.

What I am doing is defining a function to define whether certain arguments are "valid", things such as

.endswith("\\")

or

.endswith(".txt")

however because they are within an if block (if __name__ == "main"`) I am struggling to work out how to stop the script there.

I basically want to apply my validation function to all the arguments and if any return False then to stop the __main__ function and show an error message in such a way:

print len(invalid_args), " arguments are invalid, please check input"

However using a break here is showing as "Break is outside of loop" in pycharm.

How can I stop the rest of my script running if validation returns False and it is all contained in the if __name__ == "__main__" block?

Here is a representation of my code, but without the unnecessary detail:

def clean():
    do_something()

def merge():
    do_something_else()

def valid()
    if valid:
        return True
    if not valid:
        return False

if __name__ == "__main__":
    if not valid():
        "Stop script here" # This is the part I don't know how to do
    if valid():
        try:
            clear()
        except Exception a e:
            print e + "Something Went Wrong"
        try:
            merge()
        except Exception as e:
            print e + "Something Went Wrong"
like image 454
Joe Smart Avatar asked Oct 25 '25 01:10

Joe Smart


1 Answers

break is used to break out of a loop (as PyCharm has told you).

Instead you could have the following code which will run your tests and if true not allow the rest of the content to proceed.

# Your code ...

def some_function():
    # Something function that runs your tests
    # If your tests fail then return True, otherwise return False

if __name__ == '__main__':
    if some_function():
        print("Sorry but your .bat file must be broken!")
    else:
        # Run the rest of your code happily.

You could even raise an Exception as opposed to just printing a message.

like image 178
Ffisegydd Avatar answered Oct 26 '25 17:10

Ffisegydd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!