Python获取脚本所有参数方法

在写python脚本中常常需要获取参数,但是如果要一下子获取所有脚本参数怎么办,有两种方法。

第一种:

import sys
str_list= [str(i) for i in sys.argv[1:]]
parameter = ' '.join(str_list)
print(parameter)

测试:
python test.py 1 2 3 4 5
结果:
1 2 3 4 5

第二种:

import sys
import getopt
opts,args = getopt.getopt(sys.argv[1:],'hi:',['help','insert='])
print(args)
测试:
python test.py 1 2 3 4 5 
结果:
['1', '2', '3', '4', '5']

getopt用法
getopt.getopt(args, options[, long_options])
第一个参数为:获取的命令行参数
第二个参数为:可以解析的option首字母组成的字符串,后面带有:表示必须要跟参数
第三个参数为:长option,字符串组成的一个list,后面加=表示需要加参数

  

  

原文地址:https://www.cnblogs.com/lucktomato/p/14972727.html