Python中sys.argv(参数、解包、变量)

猿友 2021-01-07 10:26:37 浏览数 (3495)
反馈

小编今天给大家介绍将变量传递给脚本的方法。

在 python 中如果要运行一个my.py脚本,只需要在命令行中运行 python my.py,这句命令中的 my.py 部分就是所谓的‘参数(argument)’,现在要做的是如何写一个可以接受参数的脚本。

from sys import argv
script , first , second , third = argvprint('the script is called ',script) print('your first variable is ',first) print('your second variable is ',second) print('your thrid variable is ',thrid) 
  • 第一行中 import 导入库,argv 就是所谓的‘参数变量(arguement variable),这个变量包含了传递给 python 的参数;
  • 第二行 argv 解包(unpack),意思为把 argv 东西解包,将所有参数依次赋予左边的变量名。

在命令行中实现 my.py 的调用必须传递三个参数

python my.py first 2nd 3nd

在终端执行时将看到以下效果:

$  python my.py first 2nd 3nd
the script is called my
your first variable is first
your second variable is 2nd
your thrid variable is 3nd

推荐好课:Python3零基础入门到爬虫实战Python自动化办公+数据可视化视频课程


0 人点赞