Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python参数计数_Python_Command Line Arguments - Fatal编程技术网

Python参数计数

Python参数计数,python,command-line-arguments,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

我刚刚接触了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在下面的一条有用的评论中指出的那样,参数也提供了更多的信息。

参数从带有
argv的C开始从0开始计数,可能在这之前。参数0是可执行文件/脚本名称,它后面的所有其他参数都从1开始。

Python的文档也很棒。这里有记录:@GregHewgill如果你同意的话,我会在我的答案中添加一个链接?@GregHewgill Point在下面被适当地注释和编辑。在旁注中,我会使用argparse,这是一种更好的方式来阅读命令行参数,并提供帮助选项。这是一些流行的python库使用的实际选项。@Joseph我想你在阅读《艰苦地学习python》,对吗?