# 这是将Python的功能模块加入你自己脚本的方法
from sys import argv
# read the wyss section for how to run this
# 将 argv进行“解包(unpack)”
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)
注意:
一定要用命令行,通过$ python ex13.py first 2nd 3rd
命令运行程序
练习
- Try giving fewer than three arguments to your script. See that error you get? See if you can explainit.
- Write a script that has fewer arguments and one that has more. Make sure you give the unpackedvariables good names.
- Combine input with argv to make a script that gets more input from a user. Don’t overthink it. Justuse argv to get something, and input to get something else from the user.
- Remember that modules give you features. Modules. Modules. Remember this because we’ll needit later.
答案
- 输入命令:
python ex13.py first 2nd
会出现以下错误:
Traceback (most recent call last):
File "ex13.py", line 3, in <module>
script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 3)
输入命令:python ex13.py first 2nd 3rd 4th
会出现以下错误:
Traceback (most recent call last):
File "ex13.py", line 3, in <module>
script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 3)
所以输入命令要根据变量的个数决定,太多太少都不行。
代码1:
from sys import argv
apple, banana, orange, pear, pineapple = argv
print("The first fruit is called", apple)
print("The sceond furit is called", banana)
print("The third fruit is called", orange)
print("The fourth furit is called", pear)
print("The fifth fruit is called", pineapple)
代码2:
from sys import argv
bear, wolf, tigger = argv
print("the bear is",bear)
print("the wolf is",wolf)
print("the tigger is",tigger)
代码:
from sys import argv
dog, cat = argv
print("the dog is called",dog)
print("the cat is called",cat)
fish = input("input name:")
print(f"the fish is called {fish}")
题目中讲了不要多虑,应该就是分开使用吧。
小结:参数, 解包, 变量
·from sys import argv·是导入模块的作用,这个模块具体的作用应该是把在命令行输入的参数打包,再在script,first,second,third = argv
中解包,分配给各个变量。命令行输入的第一个参数一定是文件名称。