91

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

#!/usr/bin/python
import sys
try:
    in_file = open(sys.argv[1], "r")
except:
    sys.exit("ERROR. Did you make a mistake in the spelling")
text = in_file.read()
print text
in_file.close()

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*)
jww
  • 97,681
  • 90
  • 411
  • 885
Dan1676
  • 1,685
  • 8
  • 24
  • 35
  • Possible duplicate of [python and sys.argv](https://stackoverflow.com/q/983201/608639) – jww Apr 01 '19 at 10:43
  • From a object orientation perspective, I can understand why argc should be coupled to argv. If these were two objects, they could be mutated interdependently of each other. It makes sense for argc to be an attribute of argv (and not of sys), I just am not sure __len__ is the defacto attribute name i would use. argv.__len__ is critical for mechanical reasons, and since its there it doesn't make a ton of sense to give it another name. I would probably have favored a sys proxy descriptor like `sys.argc = property(lambda self: len(self.argv)).__get__(sys, sys.__class__)` though – ThorSummoner Jan 18 '20 at 01:09

4 Answers4

150

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

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • import sys # count the arguments arguments = len(sys.argv) - 1 print ("the script is called with %i arguments" % (arguments)) – Teo Nov 22 '19 at 10:57
19

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.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
8

You're better off looking at argparse for argument parsing.

http://docs.python.org/dev/library/argparse.html

Just makes it easy, no need to do the heavy lifting yourself.

Nickle
  • 367
  • 3
  • 5
0

dir(sys) says no. len(sys.argv) works, but in Python it is better to ask for forgiveness than permission, so

#!/usr/bin/python
import sys
try:
    in_file = open(sys.argv[1], "r")
except:
    sys.exit("ERROR. Can't read supplied filename.")
text = in_file.read()
print(text)
in_file.close()

works fine and is shorter.

If you're going to exit anyway, this would be better:

#!/usr/bin/python
import sys
text = open(sys.argv[1], "r").read()
print(text)

I'm using print() so it works in 2.7 as well as Python 3.

Cees Timmerman
  • 17,623
  • 11
  • 91
  • 124
  • I like "better to ask forgiveness than permission" for most cases in Python. In the case of command line args though, an arguably better user experience would be to show the command line arguments that are required for the Python script if the wrong number of arguments are present. – DoomGoober Jul 23 '20 at 20:28
  • @DoomGoober "supplied filename" is the argument it expects. – Cees Timmerman Jul 25 '20 at 23:58