Python3 getopt 接收长短参数

428 阅读1分钟
  •        Python : 3.8.11
  •          OS : Ubuntu Kylin 20.04
  •       Conda : 4.10.1
  •     Pycharm : 2021.1.3

代码示例

import sys
import getopt

print(sys.argv)

print(sys.argv[1:])

try:
    # getopt(args, options[, long_options]) -> opts, args
    # -a: a有接收值
    # num_a=: 长参数接收值
    opts, args = getopt.getopt(sys.argv[1:],
                               shortopts="a:b:h",
                               longopts=['num_a=', 'num_b=', 'help'])
    print(opts)
    print(args)

    for o, a in opts:
        print(o, a)
        if o in ("-a", "--num_a"):
            print("num_a=", a)
        elif o in ("-b", "--num_b"):
            print("num_b=", a)
        elif o in ("-h","--help"):
            print("help")
except getopt.GetoptError as err:
    print("GetoptError", str(err))
except Exception as err:
    print("Exception", str(err))

运行效果

(base) coder@ubuntu:~/PycharmProjects/pythonProject3$ python main.py -a 500 -b 100 -h
['main.py', '-a', '500', '-b', '100', '-h']
['-a', '500', '-b', '100', '-h']
[('-a', '500'), ('-b', '100'), ('-h', '')]
[]
-a 500
num_a= 500
-b 100
num_b= 100
-h 
help
(base) coder@ubuntu:~/PycharmProjects/pythonProject3$ python main.py --num_a=500 --num_b=100 --help
['main.py', '--num_a=500', '--num_b=100', '--help']
['--num_a=500', '--num_b=100', '--help']
[('--num_a', '500'), ('--num_b', '100'), ('--help', '')]
[]
--num_a 500
num_a= 500
--num_b 100
num_b= 100
--help 
help

学习推荐


Python具有开源、跨平台、解释型、交互式等特性,值得学习。
Python的设计哲学:优雅,明确,简单。提倡用一种方法,最好是只有一种方法来做一件事。
代码的书写要遵守规范,这样有助于沟通和理解。
每种语言都有独特的思想,初学者需要转变思维、踏实践行、坚持积累。