Does Python have an argc argument?


I have written the same program (open text file and display contents) in C and C++. Now am doing the same in Python (on a Linux machine).

In the C programs I used the code:

if (argc != 2) {
    /* exit program */

Question: What is used in Python to check the number of arguments

import sys
    in_file = open(sys.argv[1], "r")
    sys.exit("ERROR. Did you make a mistake in the spelling")
text =
print text

Current output:

./python names.txt = Displays text file (correct)
./python nam = error message: stated from the sys.ext line (correct)
./python = error message: stated from the sys.ext line (wrong: want it to be a
separate error message stating *no file name input*)
4/1/2019 10:39:37 AM

Accepted Answer

In python a list knows its length, so you can just do len(sys.argv) to get the number of elements in argv.

11/20/2011 1:54:54 PM

I often use a quick-n-dirty trick to read a fixed number of arguments from the command-line:

[filename] = sys.argv[1:]

in_file = open(filename)   # Don't need the "r"

This will assign the one argument to filename and raise an exception if there isn't exactly one argument.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow