kwicz
kwicz

Reputation: 73

Exiting with 1 in Python

This is one of my first programs in Python, so I might be missing something obvious.

In this first part of my code that I've posted, I'd like to make sure the user passes a command line argument. If not, I want to show an error and return 1. When I run the code without a command line argument, the program has the expected behavior because the error prints and the program exits.

However, when I run a checker on this, I get an error:

handles lack of argv[1]. expected exit code 1, not 0.

Any ideas on what I may be missing?

import sys
import cs50
from cs50 import get_string


def main(argv):
    # Check for command line argument
    if (len(sys.argv) != 2):
        print("Error: Please input numeric key in command line.")
        return 1

if __name__ == "__main__":
    main(sys.argv)

Upvotes: 6

Views: 2988

Answers (1)

ndmeiri
ndmeiri

Reputation: 5039

In a blog post, Guido van Rossum, the creator of Python, suggests writing the if __name__ == "__main__" block like this:

if __name__ == "__main__":
    sys.exit(main())

This way, main() can return a value, like a normal function, and it will be used as an exit code for the process.

I suggest reading the rest of that blog post. It contains helpful suggestions for setting up Python main() function boilerplate to be more flexible.

Upvotes: 9

Related Questions