解析用户输入的简单命令行应用程序



这里是python的新手-我想创建一个命令行应用程序,用户将在其中键入输入,我将解析它并执行一些命令-在以下行中:

try:
    while True:
        input = raw_input('> ')
        # parse here
except KeyboardInterrupt:
    pass

用户应该输入像init /path/to/dir这样的命令。我可以用argparse来解析这些吗?我的方式是不是太粗糙了?

您可以查看cmd库:http://docs.python.org/library/cmd.html


如果您想自己解析,您可以使用split对用户输入进行标记,并根据标记执行命令,类似于:

try:
    while True:
        input = raw_input('> ')
        tokens = input.split()
        command = tokens[0]
        args = tokens[1:]
        if command == 'init':
            # perform init command
        elif command == 'blah':
            # perform other command

except KeyboardInterrupt:
    pass

arparse是您建议的完美解决方案。文档写得很好,并展示了几十个如何简单调用它的示例。记住,它想读sys。所以当你调用parse_args时,你想给它args (https://docs.python.org/2.7/library/argparse.html?highlight=argparse#the-parse-args-method)。

唯一缩小的是argparse期望条目采用"parameter"格式,即以破折号为前缀。

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-init', nargs=1)
>>> parser.parse_args('-init /path/to/something'.split())
Namespace(init="/path/to/something")

这取决于您想要做什么,但是您可以让脚本使用ipython(交互式python)。例如:

    #!/bin/ipython -i
    def init(path_to_dir):
        print(path_to_dir)

用法:脚本启动后,

init (pathToFile.txt)

你在一个交互式的python会话中运行,所以你得到了像选项卡完成这样的功能,这是很难手工实现的。另一方面,你被python语法困住了。这取决于你的应用。

我所做的是:

# main
parser = Parser('blah')
try:
    while True:
        # http://stackoverflow.com/a/17352877/281545
        cmd = shlex.split(raw_input('> ').strip())
        logging.debug('command line: %s', cmd)
        try:
            parser.parse(cmd)
        except SystemExit: # DUH http://stackoverflow.com/q/16004901/281545
            pass
except KeyboardInterrupt:
    pass

其中解析器:

class Parser(argparse.ArgumentParser):
    def __init__(self, desc, add_h=True):
        super(Parser, self).__init__(description=desc, add_help=add_h,
                                     formatter_class=argparse.
                                    ArgumentDefaultsHelpFormatter)
        # https://docs.python.org/dev/library/argparse.html#sub-commands
        self.subparsers = subparsers = self.add_subparsers(
            help='sub-command help')
        # http://stackoverflow.com/a/8757447/281545
        subparsers._parser_class = argparse.ArgumentParser
        from  watcher.commands import CMDS
        for cmd in CMDS: cmd()(subparsers)
    def parse(self, args):
        return self.parse_args(args)

和一个命令(CMDS=[watch.Watch]):

class Watch(Command):
    class _WatchAction(argparse.Action):
        def __call__(self, parser, namespace, values, option_string=None):
            # here is the actual logic of the command
            logging.debug('%r %r %r' % (namespace, values, option_string))
            setattr(namespace, self.dest, values)
            Sync.addObserver(path=values)
    CMD_NAME = 'watch'
    CMD_HELP = 'Watch a directory tree for changes'
    ARGUMENTS = {'path': Arg(hlp='Path to a directory to watch. May be '
                                  'relative or absolute', action=_WatchAction)}

地点:

class Command(object):
    """A command given by the users - subclasses must define  the CMD_NAME,
    CMD_HELP and ARGUMENTS class fields"""
    def __call__(self, subparsers):
        parser_a = subparsers.add_parser(self.__class__.CMD_NAME,
                                         help=self.__class__.CMD_HELP)
        for dest, arg in self.__class__.ARGUMENTS.iteritems():
            parser_a.add_argument(dest=dest, help=arg.help, action=arg.action)
        return parser_a
class Arg(object):
    """Wrapper around cli arguments for a command"""
    def __init__(self, hlp=None, action='store'):
        self.help = hlp
        self.action = action
到目前为止,

只尝试了一个命令,所以这是相当未经测试的。我使用了注释中的shlex和子解析器技巧。我看了看@jh314建议的cmd模块,但并没有完全理解它-但我认为这是工作的工具-我对代码做我所做的事情的答案感兴趣,但使用cmd模块。

最新更新