python中的简单命令行应用程序-解析用户输入? [英] Simple command line application in python - parse user input?
问题描述
这里是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库: 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屋!