美文网首页
Python argv函数简介

Python argv函数简介

作者: ljZhang416 | 来源:发表于2019-06-02 22:47 被阅读0次

如果想对python脚步传参数,那么就需要命令行参数的支持了,这样可以省的每次去改脚步了。
例如:

from sys import argv

pyname, one, two, three = argv
print("python file name is :", pyname)
print("The first word is :", one)
print("The second word is :", two)
print("The third word is :", three)

这个脚本运行时,如果直接输入:

python ex13.py

返回结果如下:

Traceback (most recent call last):
  File "ex13.py", line 3, in <module>
    pyname, one, two, three = argv
ValueError: not enough values to unpack (expected 4, got 1)

因为要求需要 4 个参数,实际只输入了一个。
正确的运行方式如下:

python ex13.py 1 3 hffhl#需连带脚本名一共有 4 个参数

输出结果如下:

python file name is : ex13.py
The first word is : 1
The second word is : 3
The third word is : hffhl

可以看到argv用法就是获取在命令行执行脚本时python命令后跟的所有参数

仔细思考一下,这里的argv 其实就是一个列表,具体看一下:

from sys import argv

pyname, one, two, three = argv
print("-------argv = ", argv)

输入如下:

python ex13.py 1 3 hffhl

返回结果是:

-------argv =  ['ex13.py', '1', '3', 'hffhl']

argv其实就是一个列表,里边的项为用户输入的参数,关键就是要明白这参数是从程序外部输入的,而非代码本身的什么地方,要想看到它的效果就应该将程序保存了,从外部来运行程序并给出参数。

相关文章

网友评论

      本文标题:Python argv函数简介

      本文链接:https://www.haomeiwen.com/subject/jvbfxctx.html