【发布时间】:2014-06-26 18:49:26
【问题描述】:
我不知道为什么会这样。据我了解,在执行默认操作之前,用户至少有机会使用 -h。
import os, sys, argparse
class argument_parser():
# call on all our file type parsers in the sequence_anlysis_method
def __init__(self):
self.db_directory = os.path.dirname(os.path.abspath(sys.argv[0]))
"""A customized argument parser that does a LOT of error checking"""
self.parser = argparse.ArgumentParser(
prog="igblast")
general = self.parser.add_argument_group(
title="\nGeneral Settings")
general.add_argument(
"-x", '--executable',
default="/usr/bin/igblastn",
type=self._check_if_executable_exists,
help="The location of the executable, default is /usr/bin/igblastn")
self.args = self.parser.parse_args()
def _check_if_executable_exists(self,x_path):
if not os.path.exists(x_path):
msg = "path to executable {0} does not exist, use -h for help\n".format(x_path)
raise argparse.ArgumentTypeError(msg)
if not os.access(x_path, os.R_OK):
msg1 = "executable {0} does have not permission to run\n".format(x_path)
raise argparse.ArgumentTypeError(msg1)
else:
return x_path
if __name__ == '__main__':
argument_class = argument_parser()
现在如果 /usr/bin/igblastn 存在,那很好,但如果不存在,调用此程序会引发 self_check_if_executable_exists 中的异常。
File "execution.py", line 220, in <module>
argument_class = ap()
File "/home/willisjr/utilities/pyig/src/arg_parse.py", line 159, in __init__
self.args = self.parser.parse_args()
File "/usr/local/lib/python2.7/argparse.py", line 1656, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "/usr/local/lib/python2.7/argparse.py", line 1678, in parse_known_args
default = self._get_value(action, default)
File "/usr/local/lib/python2.7/argparse.py", line 2203, in _get_value
raise ArgumentError(action, msg)
argparse.ArgumentError: argument -x/--executable: path to executable /usr/bin/igblastn does not exist, use -h for help
据我了解,用户总是有机会运行 --help 或 -h 或在采取任何导致此参数错误的操作之前。是不是我对arg解析器的理解不清楚?
【问题讨论】:
-
它在解析开始之前通过您的自定义类型运行您的默认文件名,然后再查看 argv。较新的版本将默认值的使用推迟到最后,并且仅在需要默认值时才使用。
-
更新版本的python?
-
3.3.1和更新版本。我不确定2.7方面。看我的回答。