Linux Python 有 argc 参数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8201955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:23:17  来源:igfitidea点击:

Does Python have an argc argument?

pythonlinuxfile-ioerror-handlingarguments

提问by Dan1676

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).

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

In the C programs I used the code:

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

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

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

问题: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()

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*)

采纳答案by sepp2k

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

在 python 中,一个列表知道它的长度,所以你可以这样做len(sys.argv)来获取argv.

回答by Marcelo Cantos

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

我经常使用快速n-dirty技巧从命令行读取固定数量的参数:

[filename] = sys.argv[1:]

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

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

filename如果不完全是一个参数,这将分配一个参数并引发异常。

回答by Cees Timmerman

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

dir(sys)说不。len(sys.argv)有效,但在 Python 中,请求宽恕比许可更好,所以

#!/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.

我正在使用,print()所以它适用于 2.7 和 Python 3。

回答by Nickle

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

您最好查看 argparse 进行参数解析。

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

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

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

只是让它变得简单,不需要自己做繁重的工作。