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条回答
欢心
2楼-- · 2020-03-20 05:01

I think this example will help you. You can pass the number of arguments you want, that is, the number of parameters is variable. :D

def main(*args):
    print("Arguments Passed: ", args)

if __name__ == '__main__':
    name_Script, *script_args = sys.argv
    print("Name of the script: ", name_Script)
    main(*script_args) #Send list of arguments
查看更多
走好不送
3楼-- · 2020-03-20 05:06

Execute the code like this:

python ch13.py first second third
查看更多
乱世女痞
4楼-- · 2020-03-20 05:11

You're trying to unpack the argv into separate values. Unpacking requires, that the exact amount of values is matched by the size of the value to unpack. Consider this:

a, b, c = [1, 2, 3]

works fine, but this:

a, b, c, d, e = [1]

will give you the same ugly error, that you just produced. Unpacking sys.argv in the way you did is especially bad, because it's user input, and you don't know, how many arguments the users of your script will supply. So you should unpack it more carefully:

if len(argv) == 5:
    script_name, a, b, c, d = argv
else:
    print "This script needs exactly four arguments, aborting"
    exit()
查看更多
贼婆χ
5楼-- · 2020-03-20 05:13

You can do

(script, first, second, third) = argv 

and pass 3 arguments

python filename arg1 arg2 arg3

when you run it from command line.

I am using Python 3.6.0. Before i was not wrapping the argv arguments in braces. But now it works.

you can check it here

查看更多
看我几分像从前
6楼-- · 2020-03-20 05:15

All you have to do is type any three things when opening the script. For example, run python (then your filename.py) 1 2 3. The "1, 2 and 3" can be replaced with any three numbers or words.

查看更多
ら.Afraid
7楼-- · 2020-03-20 05:17

You forgot to pass arguments to the script, e.g. foo.py bar baz quux.

enter image description here

查看更多
登录 后发表回答