mdmenard
mdmenard

Reputation: 253

Checking the number of command line arguments in Python

I'm new to Python. Still getting my feet wet. I'm trying to do something like this:

import sys

if ((len(sys.argv) < 3 or < len(sys.argv > 3)):
    print """\
This script will compare two files for something
and print out matches

Usage:  theScript firstfile secondfile
"""
    return

I want to do this at the beginning of the script to check for the right number of arguments.

The problem is return doesn't work here. I could do some big if-then statement I suppose, but was hoping to not have to do that. Not sure if there is any easier way.

Any ideas?

Upvotes: 21

Views: 61751

Answers (2)

gariepy
gariepy

Reputation: 3674

Use sys.exit() to exit from a script.

import sys

if len(sys.argv) != 3:
    print """\
This script will compare two files for something
and print out matches

Usage:  theScript firstfile secondfile
"""
    sys.exit(0)

Upvotes: 20

zondo
zondo

Reputation: 20346

sys has a function called exit:

sys.exit(1)

is probably what you want. Using 1 tells the program calling your program that there was an error. You should probably consider writing to sys.stderr the reason for the error.

Upvotes: 4

Related Questions