argparse模块
argparse是python用于解析命令行参数和选项的标准模块
导入argparse包
import argparse
遇到的问题
parser = argparse.ArgumentParser()
parser.parse_args()
usage: __main__.py [-h]
__main__.py: error: unrecognized arguments: -f /run/user/1006/jupyter/kernel-ce6cfb61-acb9-40bf-a59b-ff6e1c1eacae.json
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
问题分析
由于在jupyter notebook中,args不为空,可以查看系统环境变量,大概是下面形式
import sys
sys.argv
['/home/liu/anaconda2/lib/python2.7/site-packages/ipykernel/__main__.py',
'-f',
'/run/user/1006/jupyter/kernel-ce6cfb61-acb9-40bf-a59b-ff6e1c1eacae.json']
可以看出,错误中的-f /…来自这里,可以查看parse_args()函数源码
以及和其调用的函数parse_known_args()源码
虽然args默认参数为None,但是实质为args = _sys.argv[1:]
所以在jupyter中,可以查看自己需要的系统环境变量,然后以list的数据形式传参给args则可以了
parser.parse_args??
parser.parse_known_args??
Signature: parser.parse_args(args=None, namespace=None)
Source:
def parse_args(self, args=None, namespace=None):
args, argv = self.parse_known_args(args, namespace)
if argv:
msg = _('unrecognized arguments: %s')
self.error(msg % ' '.join(argv))
return args
File: /home/liu/anaconda2/lib/python2.7/argparse.py
Type: instancemethod
Signature: parser.parse_known_args(args=None, namespace=None)
Source:
def parse_known_args(self, args=None, namespace=None):
if args is None:
# args default to the system args
args = _sys.argv[1:]
else:
# make sure that args are mutable
args = list(args)
# default Namespace built from parser defaults
if namespace is None:
namespace = Namespace()
# add any action defaults that aren't present
for action in self._actions:
if action.dest is not SUPPRESS:
if not hasattr(namespace, action.dest):
if action.default is not SUPPRESS:
setattr(namespace, action.dest, action.default)
# add any parser defaults that aren't present
for dest in self._defaults:
if not hasattr(namespace, dest):
setattr(namespace, dest, self._defaults[dest])
# parse the arguments and exit if there are any errors
try:
namespace, args = self._parse_known_args(args, namespace)
if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
return namespace, args
except ArgumentError:
err = _sys.exc_info()[1]
self.error(str(err))
File: /home/liu/anaconda2/lib/python2.7/argparse.py
Type: instancemethod
问题解决
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args(args=[])
print(args)
Namespace(verbosity=None)