Python sys.argv的用法
Admin
2019-05-05 18:15:51
Python
sys.argv[]是用来获取命令行参数的,sys.argv[0]表示代码本身文件路径,因此要从第二个即sys.argv[1]开始取参数。
注意:参数是以空格分开的
创建一个名为argvs.py的文件,内容如下:
import sys print('the first argv: ',sys.argv[0],'\n') # 显示第一个参数 print('the second argv: ',sys.argv[1],'\n') # 显示第二个参数 print('the third argv: ',sys.argv[2],'\n') # 显示第三个参数 # 以此类推执行的结果如下 python argvs.py ping pong the first argv: /User/zz/argvs.py # python文件的路径 the second argv: ping # --参数1 the third argv: pong # --参数2
判断参数1是否是以‘--’开头
if sys.argv[1].startswith('--'): ption = sys.argv[1][2:] # 把参数1从第三个字符开始的字符串赋值给option(去掉‘--’字符)直到参数1后面的空格。 if ption == 'v': print ('Version 1.2') elif option == 'h': print ('This program prints files to the standard output. Options include: --v : Prints the version number --h : Display this help')
python argvs.py --h the first argv: /User/zz/argvs.py the second argv: --h This program prints files to the standard output. Options include: --v : Prints the version number --h : Display this help python argvs.py --v the first argv: /User/zz/argvs.py the second argv: --v Version 1.2