Python 参数计数

标签 python command-line-arguments

我刚接触 Python 中的参数,我发现 Python 中参数系统的工作方式很奇怪(我不确定其他语言)。例如:

from sys import argv

arg1, arg2, arg3 = argv

print "First argument: ", arg1
print "Second argument: ", arg2
print "Third argument: ", arg3

当我在命令行中使用以下参数运行它时:

python example.py First Second

它给出了输出:

First argument: example.py
Second argument: First
Third argument: Second

这是否意味着 python 从零开始计数?还是这样做有一些不同或更多的原因。这很奇怪,但很有趣。

最佳答案

是的,正如您推测的那样,Python 使用从零开始的索引(许多其他编程语言也这样做)。

sys.argv 是一个字符串列表。

sys.argv[0] 将包含脚本的名称,此字符串列表中的后续条目将包含提供给脚本的命令行参数。

我本来打算提供一个示例,但您帖子中的内容与我所能想到的一样好。

最后,正如@GregHewgill 在下面的有用评论中指出的那样,Python docs也提供更多相关信息。

关于Python 参数计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11926995/

相关文章:

c - 如何在 C 语言的 shell 中执行带有多个参数的命令?

python - 如何在 Python 中读取整数命令行参数?

python - 内存中的数据大小与磁盘上的数据大小

C++软件传递参数方法

python - 在 wxPython 中进行拖放的 OLE 方式

Python 格式最佳实践

c++ - 使用 char** argv 时如何避免指针运算

shell - 如何插入作为参数发送的字符串?

python - Vim - 如何在 python shell 中运行当前的 python3 文件?

python - 限制 Tkinter Entry 小部件中的值 : Why can't I delete the first character?