Python 有 argc 参数吗?

我用 C 和 C + + 编写了相同的程序(打开文本文件和显示内容)。现在我正在 Python (在 Linux 机器上)中做同样的事情。

在 C 语言程序中,我使用了以下代码:

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

问: Python 中使用了什么来检查参数的数量

#!/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()

目前产出:

./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*)
122555 次浏览

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

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.

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.

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.