我想知道同样的事情...并认为是“单例”,但是鉴于您打算跨模块共享参数...如果您创建一个 base_argparse 模块以通过 base_argparse.ArgumentParser 共享一个单例是有意义的,然后可以将其用作argparse.ArgumentParser 的替代品。
我确实尝试过Creating a singleton in Python,但它似乎有点矫枉过正。 (特别是如果你想在模块间共享)
如果你找到更好的方法,请告诉我...
文件:base_argparse.py
import argparse
_singleton=None
_description=""
def ArgumentParser(description=None, *arg_l, **arg_d):
global _singleton, _description
if description:
if _description: _description+=" & "+description
else: _description=description
if _singleton is None: _singleton=argparse.ArgumentParser(description=_description, *arg_l, **arg_d)
return _singleton
文件:module_x.py
import sys
import base_argparse
parser = base_argparse.ArgumentParser(description='Module_X Arguments')
parser.add_argument('-x', action="store_true", default=False)
if __name__=="__main__":
opt_ns=parser.parse_args(sys.argv[1:])
print opt_ns,opt_ns.x
文件:module_y.py
import sys
import base_argparse
parser = base_argparse.ArgumentParser(description='Module_Y Arguments')
parser.add_argument('-y', action="store", dest="y")
if __name__=="__main__":
opt_ns=parser.parse_args(sys.argv[1:])
print opt_ns,opt_ns.y
文件:module_z.py
import sys
import base_argparse
parser = base_argparse.ArgumentParser(description='Module_Z Arguments')
parser.add_argument('-z', action="store", dest="z", type=int)
if __name__=="__main__":
opt_ns=parser.parse_args(sys.argv[1:])
print opt_ns,opt_ns.z
文件:test_argparse.py
import sys
import base_argparse
# in main ...
parser = base_argparse.ArgumentParser(description='Test Arguments')
# then the matching load modules
import module_x,module_y,module_z
if __name__=="__main__":
parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)
opt_ns=parser.parse_args(sys.argv[1:])
print opt_ns,opt_ns.a,opt_ns.b,opt_ns.c,opt_ns.x,opt_ns.y,opt_ns.z
测试用例:
$ python test_argparse.py
Namespace(a=False, b=None, c=None, x=False, y=None, z=None) False None None False None None
$ python module_x.py -x
Namespace(x=True) True
$ python module_x.py -a -b 2 -c 3 -x -y 25 -z 26
usage: module_x.py [-h] [-x]
module_x.py: error: unrecognized arguments: -a -b 2 -c 3 -y 25 -z 26
$ python test_argparse.py -a -b 2 -c 3
Namespace(a=True, b='2', c=3, x=False, y=None, z=None) True 2 3 False None None
$ python test_argparse.py -x -y 25 -z 26
Namespace(a=False, b=None, c=None, x=True, y='25', z=26) False None None True 25 26
$ python test_argparse.py -a -b 2 -c 3 -x -y 25 -z 26
Namespace(a=True, b='2', c=3, x=True, y='25', z=26) True 2 3 True 25 26