在程序中要用到argparse模块的相关功能,之前没有使用过,在此记录一下。
1.py:
import argparse
class M:
def m1(self):
print("m1")
def m2(self):
print("m2")
class N:
def n1(self):
print("n1")
def n2(self):
print("n2")
def attach1():
m = M()
m.m1()
m.m2()
def attach2():
n = N()
n.n1()
n.n2()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-a1", "--attach1", action="store_true", required=False, help="a1参数说明")
parser.add_argument("-a2", "--attach2", action="store_true", required=False, help="a2参数说明")
args = parser.parse_args()
isa1 = args.attach1
isa2 = args.attach2
if isa1:
attach1()
if isa2:
attach2()
# 执行示例:
> python 1.py --help
usage: 1.py [-h] [-a1] [-a2]
optional arguments:
-h, --help show this help message and exit
-a1, --attach1 a1参数说明
-a2, --attach2 a2参数说明
> python 1.py -a1
m1
m2
> python 1.py -a2
n1
n2
> python 1.py -a1 -a2
m1
m2
n1
n2