如果我将 argv 初始化为 third 以外的任何其他变量,我会收到错误消息
If I initialize argv to any other variable other than third, I get an error
这是来自 Zed A. Shaw 的 "Learning python the hard way" 的片段。当我将第一个或第二个变量初始化为 argv 时,出现错误。我还没有找到对此的解释。
from sys import argv
script, first, second, third=argv
print "the script is called:",script
print "your first variable is called ",first
print "your second variable is called ",second
print "your third variable is called ",third
我可以复制错误以查看发生了什么错误吗?
当我执行上面的代码时,它运行正常。
不使用逗号
Argv 检查 space。
$ python b.py 1 2 3
the script is called: b.py
your first variable is called 1
your second variable is called 2
your third variable is called 3
版本
⚡ root@dev # uname -a
Linux dev 4.4.0-1031-aws #40-Ubuntu SMP Thu Aug 10 11:29:58 UTC 2017 x86_64
x86_64 x86_64 GNU/Linux
⚡ root@dev # cat /etc/issue
Ubuntu 16.04.2 LTS \n \l
⚡ root@dev # python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
您没有初始化第三个参数。你正在解压 argv。 a,b,c = argv
就像 a = argv[0]; b = argv[1]; c = argv[2];...
如果你想在参数之间使用逗号,你总是需要给出一个space,否则编译器认为1,2,3
是一个参数,因此错误:
ValueError: need more than 2 values to unpack
像这样调用脚本:
python ex13.py a, b, c
这是来自 Zed A. Shaw 的 "Learning python the hard way" 的片段。当我将第一个或第二个变量初始化为 argv 时,出现错误。我还没有找到对此的解释。
from sys import argv
script, first, second, third=argv
print "the script is called:",script
print "your first variable is called ",first
print "your second variable is called ",second
print "your third variable is called ",third
我可以复制错误以查看发生了什么错误吗?
当我执行上面的代码时,它运行正常。
不使用逗号
Argv 检查 space。
$ python b.py 1 2 3
the script is called: b.py
your first variable is called 1
your second variable is called 2
your third variable is called 3
版本
⚡ root@dev # uname -a
Linux dev 4.4.0-1031-aws #40-Ubuntu SMP Thu Aug 10 11:29:58 UTC 2017 x86_64
x86_64 x86_64 GNU/Linux
⚡ root@dev # cat /etc/issue
Ubuntu 16.04.2 LTS \n \l
⚡ root@dev # python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
您没有初始化第三个参数。你正在解压 argv。 a,b,c = argv
就像 a = argv[0]; b = argv[1]; c = argv[2];...
如果你想在参数之间使用逗号,你总是需要给出一个space,否则编译器认为1,2,3
是一个参数,因此错误:
ValueError: need more than 2 values to unpack
像这样调用脚本:
python ex13.py a, b, c