Using command line arguments in Python: Understand

2020-03-20 04:39发布

I'm currently going through Learn Python The Hard Way. I think this example might be out dated so I wanted to get feedback here on it.

I'm using Python 3.1

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))

I'm getting this error:

Traceback (most recent call last):
  File "/path/ch13.py", line 3, in <module>
    script, first, second, third, bacon = argv
ValueError: need more than 1 value to unpack

Any idea what's wrong?

10条回答
forever°为你锁心
2楼-- · 2020-03-20 05:19

sys.arg is a list of command line parameters. You need to actually pass command line parameters to the script to populate this list. Do this either in your IDE's project settings or by running like this on the command line:

python script.py first second third

Note that the first argument is always the script's name (python script.py in this case). Due to your usage of unpacking, you will get a ValueError whenever you pass fewer or more than 3 parameters. You can check the number before unpacking using len(argv)-1 and presenting a suitable error if not 3.

On a related note, look at getopt if you need to do more complex argument passing.

查看更多
淡お忘
3楼-- · 2020-03-20 05:19

In order to run this script on the command line, you need to use three arguments. You will have to type something similar to the following:

python /path/ch13.py first second third
查看更多
狗以群分
4楼-- · 2020-03-20 05:21
from sys import argv
a, b, c, d = argv
print "The script is called:", a
print "Your first variable is:", b
print "Your second variable is:", c
print "Your third variable is:", d

Save this script as: s.py

Run this script from terminal as follows: enter image description here

查看更多
我命由我不由天
5楼-- · 2020-03-20 05:24

In order to pass arguments, you will need to run the script in this manner:

python fileName.py argument1 argument2

Depending on how many variables you have = to argv, this is how many you need to have minus the first argument (script). E.g.,

 script, first, second, third = argv

should have 3 arguments.

查看更多
登录 后发表回答