美文网首页
python 命令行 读取参数

python 命令行 读取参数

作者: 偷油考拉 | 来源:发表于2022-04-21 18:24 被阅读0次

1、命令行后接参数

import sys
print ("The Script Name is :  ",sys.argv[0])
print ("Current Arguments num is :  ",len(sys.argv))
for i in range(1,len(sys.argv)):
    print ("Argument num ", i, "is:", sys.argv[i])
[root@VM-99-12-centos]# python3 test.py 1 2 3
The Script Name is :   test.py
Current Arguments num is :   4
Argument num  1 is: 1
Argument num  2 is: 2
Argument num  3 is: 3

问题:不作解析,比如:

[root@VM-99-12-centos tencent-004-主机安全]# python3 test.py -f  2 3
The Script Name is :   test.py
Current Arguments num is :   4
Argument num  1 is: -f
Argument num  2 is: 2
Argument num  3 is: 3

2、 getopt — C-style parser for command line options

简单处理命令行参数
getopt.getopt(args, shortopts, longopts=[])
exception getopt.GetoptError

import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        else:
            assert False, "unhandled option"
    # ...

if __name__ == "__main__":
    main()

3、 argparse — Python标准库推荐的命令行解析模块

更少的代码,更多的信息,更容易的编写用户友好的命令行接口。
Argparse 官方文档

代码范例:

import argparse

parser = argparse.ArgumentParser(description='Test Argparse.')
parser.add_argument('-u', type=str,
                    help='CVM uuid , example: 2415d1da-b34e-435e-8b6c-1015e0244497 ')
parser.add_argument('-f', type=argparse.FileType('r'),
                    help='file includes uuids')

args = parser.parse_args()

print(args)

uuids = []

if args.u:
    uuid = args.u
    print("-u option, uuid is : ",uuid)
    uuids.append(uuid)
elif args.f:
    with args.f as f:
        for uuid in f.readlines():
            uuid = uuid.strip('\n')
            print("-f option,uuid is : ",uuid)
            uuids.append(uuid)


print("The end uuids array are: ",uuids)

执行结果:

[root@VM-99-12-centos tencent-004-主机安全]# python3 test_argparse.py -u ddd-ddd-ddd
Namespace(f=None, u='ddd-ddd-ddd')
-u option, uuid is :  ddd-ddd-ddd
The end uuids array are:  ['ddd-ddd-ddd']
[root@VM-99-12-centos tencent-004-主机安全]# python3 test_argparse.py -f cvmfile
Namespace(f=<_io.TextIOWrapper name='cvmfile' mode='r' encoding='UTF-8'>, u=None)
-f option,uuid is :  2415d1da-b34e-435e-8b6c-1015e0244497
-f option,uuid is :  2415d1da-b34e-435e-8b6c-1015e0244498
-f option,uuid is :  2415d1da-b34e-435e-8b6c-1015e0244499
The end uuids array are:  ['2415d1da-b34e-435e-8b6c-1015e0244497', '2415d1da-b34e-435e-8b6c-1015e0244498', '2415d1da-b34e-435e-8b6c-1015e0244499']

cvmfile 内容如下:
[root@VM-99-12-centos 004-主机安全]# cat cvmfile
2415d1da-b34e-435e-8b6c-1015e0244497
2415d1da-b34e-435e-8b6c-1015e0244498
2415d1da-b34e-435e-8b6c-1015e0244499

相关文章

网友评论

      本文标题:python 命令行 读取参数

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