当前位置: 代码迷 >> 综合 >> Python获取输入的方法之参数
  详细解决方案

Python获取输入的方法之参数

热度:14   发布时间:2024-01-24 23:30:37.0

参数、解包、变量

# -- coding: utf-8 --from sys import argv   # import 将 python 的模组(modules)sys 引入脚本(arg0, arg1, arg2, arg3) = argv   # 把 argv 中的东西解包(unpack),将所有的参数依次赋予左边的变量名print("The script is called: ", arg0)
print("Your first variable is: ", arg1)
print("Your second variable is: ", arg2)
print("Your third variable is: ", arg3)

正确用法: python .\argument.py 1 2 3

The script is called:  .\argument.py
Your first variable is:  1
Your second variable is:  2
Your third variable is:  3

错误用法

1. 参数太多:python .\argument.py 1 2 3 4

Traceback (most recent call last):File ".\argument.py", line 5, in <module>(arg0, arg1, arg2, arg3) = argv   # 把 argv 中的东西解包(unpack),将所有的参数依次赋予左边的变量名
ValueError: too many values to unpack (expected 4)

2. 参数太少: python .\argument.py 1 2

Traceback (most recent call last):File ".\argument.py", line 5, in <module>(arg0, arg1, arg2, arg3) = argv   # 把 argv 中的东西解包(unpack),将所有的参数依次赋予左边的变量名
ValueError: not enough values to unpack (expected 4, got 3)

 

  相关解决方案