python 用户输入命令_python中的简单命令行应用程序-解析用户输入?

该博客讨论了如何在Python中创建一个命令行应用程序,用户可以输入指令,然后通过解析这些指令来执行相应的操作。文章建议使用split()函数拆分用户输入的令牌,并根据这些令牌执行不同的命令,如'init'或'blah'。它还提到了处理KeyboardInterrupt异常的机制。
摘要由CSDN通过智能技术生成

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

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

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值