原文链接:http://learnpythonthehardway.org/book/ex13.html
在这次练习中我们将介绍一个新的向一个脚本中传递变量的方法(脚本就是你.py文件的别称)。你应该知道了输入了 python ex13.py 来运行 ex13.py文件了吧?这个命令的ex13.py 的这部分就是被称作“参数”。现在我们要做的就是写一个也可以介绍参数的脚本。
输入下面这个程序,我将详细的讲解这个例子:
from sys import argv
script ,first ,second ,third = argv
print "The script is called:" , script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
在第一行我们有一个“import”语句。这是用来让你从Python功能集中来添加功能到你的脚本中。与其把所有功能都一次性给你,Python更喜欢问你打算用什么功能。这样就可以使得你的程序尽量精简,而后面的程序员看到你的代码的时候,这些“import”可以作为提示,让他们明白你的代码用到了哪些功能。
argv 就是“参数变量“ ,一个你也可以在许多其他编程语言中写的程序中找到的非常标准命名术语。当你运行Python脚本的时候这个变量加载了你传进脚本的参数值。通过后面的练习你将对它进一步了解。
第三行 是对 argv 的”解析“,与其把所有变量放到一个变量中,我们把这个分成四个分别放入: script ,first ,secon 和 third四个变量中。这可能看起来有些奇怪,但是”解析“这个词可能是最适合来描述这种操作的含义了。它的意思就好比:不管你从 argv 中拿到什么,解析它 ,并把所有解析到的值按顺序赋给左边的所有变量。
接下来就是来正常打印出它们的结果。
等一下!“功能”还有另一个名字
输出结果如下:
c:\>python ex13.py first 2nd 3rd
The script is called: ex13.py
Your first variable is: first
Your second variable is: 2nd
Your third variable is: 3rd
下面这些是当你输入不同参数运行时输出不同的结果示例:
c:\>python ex13.py stuff things that
The script is called: ex13.py
Your first variable is: stuff
Your second variable is: things
Your third variable is: that
c:\>python ex13.py apple orange grapefruit
The script is called: ex13.py
Your first variable is: apple
Your second variable is: orange
Your third variable is: grapefruit
实际上你可以用任何你想要的三样东西去替代 "first" ,"2nd" 和"3rd"
c:\>python ex13.py first 2nd
Traceback (most recent call last):
File "ex13.py", line 3, in <module>
script ,first ,second ,third = argv
ValueError: need more than 3 values to unpack
出现这种错的情况是当你没有在命令行中输入足够的参数(在这里你只输入了 first 2nd ,还缺少一个参数)的时候发生的。注意到当你只给了 first 2nd两个参数时,给出的错误提示中”need more than 3 values to unpack“就是告诉你输入的参数个数不够。