0
点赞
收藏
分享

微信扫一扫

Python笔记-脚本参数传递


编写Python脚本,经常需要从外部传递参数,此时需要用到 getopt 和 sys。
语法如下:
getopt.getopt(args, shortopts, longopts=[])
args 参数列表
shortopts 短参数,如:-h
longopts 长参数,如:–help

sys.argv[] 是一个列表,包含命令行所有信息
sys.argv[0] 是被调用的脚本文件名或全路径
sys.argv[1:] 之后的元素就是我们从程序外部输入的

示例:

import getopt
import sys

def print_help():
print('\n-a value of a')
print('\n-b value of b')
print('\n-c value of c')
print()

value_a = ''
value_b = ''
value_c = ''

if len(sys.argv) <= 1:
print("\n -h --help\n")
sys.exit()
try:
opts,args=getopt.getopt(sys.argv[1:],"a:b:c",['help'])
except getopt.GetoptError:
print_help()
sys.exit
else:
for opt,arg in opts:
if opt == '-a':
value_a = arg
if opt == '-b':
value_b = arg
if opt == '-c':
value_c = arg
if opt in ('-h','--help'):
print_help()
sys.exit

if len(value_a) > 0:
print("Value_a is:",value_a)
if len(value_b) > 0:
print("Value_b is:",value_b)
if len(value_c) > 0:
print("Value_c is:",value_c)

[root@test1 dataC]# python3 test.py 

-h --help

[root@test1 dataC]# python3 test.py -h

-a value of a

-b value of b

-c value of c

[root@test1 dataC]# python3 test.py --help

-a value of a

-b value of b

-c value of c

[root@test1 dataC]# python3 test.py -a a1
Value_a is: a1
[root@test1 dataC]# python3 test.py -a b1
Value_a is: b1
[root@test1 dataC]# python3 test.py -c c1
[root@test1 dataC]# python3 test.py -x

-a value of a

-b value of b

-c value of c
[root@test1 dataC]# python3 test.py -a 1 -b 2 -c 3
Value_a is: 1
Value_b is: 2

Tips:
参数c后面没有冒号,因此 -c 后参数没有被传递。


举报

相关推荐

0 条评论