Python 中 argv 与 raw_input() 的区别详解
在 Python 编程中,获取用户输入主要有两种方式:通过命令行参数(argv)和在脚本运行时交互式输入(raw_input())。它们的区别在于要求用户输入的位置不同。如果你想让用户在命令行输入你的参数,你应该使用 argv;如果你希望用户在脚本执行的过程中输入参数,那就用到 raw_input()。
argv 的使用
argv 是 sys 模块提供的参数变量,包含了传递给 Python 脚本的参数。它是一个非常标准的编程术语,在其他编程语言里也可以看到。
import sys
script, first, second, third = sys.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)
将你的脚本运行起来:
$ 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
如果你每次输入的参数不一样,那你看到的输出结果也会略有不同:
$ 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
$ 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 替换成任意你喜欢的 3 个参数。如果你没有运行对,你可能会看到的错误信息:
$ python ex13.py first 2nd
Traceback (most recent call last):
File "ex13.py", line 3, in <module>
script, first, second, third = sys.argv
ValueError: need more than 3 values to unpack
代码的第 3 行将 argv 进行'解包(unpack)',与其将所有参数放到同一个变量下面,我们将每个参数赋予一个变量名:script, first, second, 以及 third。它的含义很简单:'把 argv 中的东西解包,将所有的参数依次赋予左边的变量名'。
raw_input() 的使用
raw_input() 用于在脚本执行过程中暂停并等待用户从键盘输入内容。这是 Python 2 中的函数,在 Python 3 中已被 input() 取代,但功能类似。
name = raw_input()
, name
name = ()
(, name)


