python中的简单命令行应用程序-解析用户输入? [英] Simple command line application in python - parse user input?

查看:35
本文介绍了python中的简单命令行应用程序-解析用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是 python 的新手 - 我想制作一个命令行应用程序,用户将在其中输入输入,我将解析它并执行一些命令 - 行中的内容:

New to python here - I want to make a command line application where the user will type input I will parse it and execute some command - something in the lines of:

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

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

The user is supposed to type commands like init /path/to/dir. Can I use argparse to parse those ? Is my way too crude ?

推荐答案

你可以看看 cmd lib: http://docs.python.org/library/cmd.html

You can take a look at the cmd lib: http://docs.python.org/library/cmd.html

如果你想自己解析,你可以使用 split 来标记用户输入,并根据标记执行你的命令,就像这样:

If you want to parse by yourself, you can use split to tokenize the user input, and execute your commands based on the tokens, sort of like this:

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

这篇关于python中的简单命令行应用程序-解析用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆