python try ... except处理用户输入中的参数

时间:2019-03-06 04:23:54

标签: python exception io try-catch argparse

我的python文件将使用argparse从命令行读取两个文件。 我想使用“ try ... except ...”来处理不正确的用户输入,例如不存在的文件和不正确的命令: 例如,我使用'-f'打开文件,那么'-g'是不正确的命令。

我的代码是:

> parser = argparse.ArgumentParser(description = "Handle with input 
files")
parser.add_argument('-m', dest = "model", type=argparse.FileType('r'))
parser.add_argument('-t', dest = "test", type=argparse.FileType('r'))
parser.add_argument('-d', dest = "permute",type=argparse.FileType('r'))
args = parser.parse_args()

# Parse file names from command line

model_file = open(args.model.name)
test_file = open(args.test.name)
decoy_file = open(args.permute.name)

我尝试在代码中实现“ try ... except”,但失败了。这是我所做的:

> parser = argparse.ArgumentParser(description = "Handle with input 
files")
parser.add_argument('-m', dest = "model", type=argparse.FileType('r'))
parser.add_argument('-t', dest = "test", type=argparse.FileType('r'))
parser.add_argument('-d', dest = "permute",type=argparse.FileType('r'))
args = parser.parse_args()

# Parse file names from command line
try:
model_file = open(args.model.name)
test_file = open(args.test.name)
decoy_file = open(args.permute.name)
except IOError:
print('Wrong file name')

3 个答案:

答案 0 :(得分:1)

我建议添加这样的内容以确保所有参数都在那里。另外,argparse.FileType('r')已经打开了文件(意味着您可以执行类似args.model.readlines()的操作)。

if not all([args.model, args.test, args.permute]):
    print("All Arguments are required")
    exit(1)

答案 1 :(得分:0)

首先,在解析命令参数时,错误发生在args = parser.parse_args()

argparse's origin code中可以看到:

    ...
    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
    ...
    def error(self, message):
        """error(message: string)

        Prints a usage message incorporating the message to stderr and
        exits.

        If you override this in a subclass, it should not return -- it
        should either exit or raise an exception.
        """
        self.print_usage(_sys.stderr)
        args = {'prog': self.prog, 'message': message}
        self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
        # exit here ,that's why can not catch the exception

因此,当您输入不正确的内容(如您上面提到的内容,例如non-exist fileincorrect command时)将最终调用error函数并退出线程,这就是为什么您不能通过try .. except synax捕获异常。

如果要捕获异常,可以继承主类ArgumentParser,然后重写方法error。您可以将我的代码作为参考:


import argparse
import sys as _sys
from argparse import ArgumentParser


class ArgumentParserSub(ArgumentParser):
    def error(self, message):
        self.print_usage(_sys.stderr)
        args = {'prog': self.prog, 'message': message}
        raise Exception(('error: %(message)s\n') % args)


parser = ArgumentParserSub(description = "Handle with input files")
parser.add_argument('-m', dest = "model", type=argparse.FileType('r'))
parser.add_argument('-t', dest = "test", type=argparse.FileType('r'))
parser.add_argument('-d', dest = "permute",type=argparse.FileType('r'))

try:
    args = parser.parse_args()
    # Parse file names from command line
    model_file = open(args.model.name)
    test_file = open(args.test.name)
    decoy_file = open(args.permute.name)

except Exception as e:
    print(e)
    print('Wrong file name')

答案 2 :(得分:0)

如果您不希望解析器捕获并退出错误的文件,请自行打开文件。只需向解析器询问名称,而不是打开文件即可。

parser = argparse.ArgumentParser(description = "Handle with input files")
parser.add_argument('-m', dest = "model")    # no type
parser.add_argument('-t', dest = "test")
parser.add_argument('-d', dest = "permute")
args = parser.parse_args()
# print(args)   # good idea when debugging

# Open file names from command line
try:
    model_file = open(args.model)
    test_file = open(args.test)
    decoy_file = open(args.permute)
except IOError:
    print('Wrong file name')