python使用argparse解析命令行参数

python例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import argparse
import os
import tarfile


untar_path = ""
out_dir = ""


def parse_usage():
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--outdir', dest='out dir')
parser.add_argument('-i', '--inpath', dest='tar path')
args = parser.parse_args()
global untar_path
global out_dir
try:
out_dir = args.outdir
untar_path = args.inpath
except:
pass

if '' == untar_path:
parser.print_help()
sys.exit()
if '' == out_dir:
parser.print_help()
sys.exit()

if not os.path.isfile(untar_path):
print("{} is not file!".format(untar_path))
sys.exit()
if os.path.exists(out_dir):
if os.path.isfile(out_dir):
print("{} is file!".format(out_dir))
sys.exit()
else:
print("mkdir {}".format(out_dir))
os.mkdir(out_dir)
if not os.path.exists(out_dir):
print("{} is not exists!".format(out_dir))
sys.exit()
print("tar({}) \nout dir({})".format(untar_path, out_dir))
return


def untar(tarpath, outdir):
tar = tarfile.open(tarpath)
tar.extractall(path = outdir)
tar.close()
return


if __name__ == "__main__":
'''main'''
parse_usage()
untar(untar_path, out_dir)

输出:

1
2
3
4
5
6
7
# untar2.py --help
usage: untar2.py [-h] [-o OUT DIR] [-i TAR PATH]

options:
-h, --help show this help message and exit
-o OUT DIR, --outdir OUT DIR
-i TAR PATH, --inpath TAR PATH

参考:

https://docs.python.org/zh-cn/3/library/argparse.html

也可以使用getopt解析命令行参数