有没有什么简单的方法来实现APT(高级包工具)命令行界面在Python中的作用?
我的意思是,当包管理器提示一个yes/no问题,后面跟着[yes/no]时,脚本接受yes/ Y/yes/ Y或Enter(默认为yes,由大写字母提示)。
我在官方文档中唯一找到的是input和raw_input…
我知道模仿它并不难,但是重写:|很烦人
有没有什么简单的方法来实现APT(高级包工具)命令行界面在Python中的作用?
我的意思是,当包管理器提示一个yes/no问题,后面跟着[yes/no]时,脚本接受yes/ Y/yes/ Y或Enter(默认为yes,由大写字母提示)。
我在官方文档中唯一找到的是input和raw_input…
我知道模仿它并不难,但是重写:|很烦人
当前回答
你可以尝试下面的代码来处理变量'accepted'中的选项:
print( 'accepted: {}'.format(accepted) )
# accepted: {'yes': ['', 'Yes', 'yes', 'YES', 'y', 'Y'], 'no': ['No', 'no', 'NO', 'n', 'N']}
这是密码。
#!/usr/bin/python3
def makeChoi(yeh, neh):
accept = {}
# for w in words:
accept['yes'] = [ '', yeh, yeh.lower(), yeh.upper(), yeh.lower()[0], yeh.upper()[0] ]
accept['no'] = [ neh, neh.lower(), neh.upper(), neh.lower()[0], neh.upper()[0] ]
return accept
accepted = makeChoi('Yes', 'No')
def doYeh():
print('Yeh! Let\'s do it.')
def doNeh():
print('Neh! Let\'s not do it.')
choi = None
while not choi:
choi = input( 'Please choose: Y/n? ' )
if choi in accepted['yes']:
choi = True
doYeh()
elif choi in accepted['no']:
choi = True
doNeh()
else:
print('Your choice was "{}". Please use an accepted input value ..'.format(choi))
print( accepted )
choi = None
其他回答
这是我对它的看法,我只是想中止如果用户没有确认的行动。
import distutils
if unsafe_case:
print('Proceed with potentially unsafe thing? [y/n]')
while True:
try:
verify = distutils.util.strtobool(raw_input())
if not verify:
raise SystemExit # Abort on user reject
break
except ValueError as err:
print('Please enter \'yes\' or \'no\'')
# Try again
print('Continuing ...')
do_unsafe_thing()
正如Alexander Artemenko提到的,这里有一个使用strtobool()的简单解决方案。
from distutils.util import strtobool
def user_yes_no_query(question):
sys.stdout.write('%s [y/n]\n' % question)
while True:
try:
return strtobool(raw_input().lower())
except ValueError:
sys.stdout.write('Please respond with \'y\' or \'n\'.\n')
使用
>>> user_yes_no_query('Do you like cheese?')
Do you like cheese? [y/n]
Only on tuesdays
Please respond with 'y' or 'n'.
ok
Please respond with 'y' or 'n'.
y
>>> True
在Python的标准库中有一个函数strtoool: http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool
您可以使用它来检查用户的输入并将其转换为True或False值。
作为一个编程新手,我发现上面的一堆答案过于复杂,特别是如果目标是有一个简单的函数,你可以传递各种是/否问题,迫使用户选择是或否。在浏览了这篇文章和其他几篇文章,并借鉴了各种各样的好想法后,我得出了以下结论:
def yes_no(question_to_be_answered):
while True:
choice = input(question_to_be_answered).lower()
if choice[:1] == 'y':
return True
elif choice[:1] == 'n':
return False
else:
print("Please respond with 'Yes' or 'No'\n")
#See it in Practice below
musical_taste = yes_no('Do you like Pine Coladas?')
if musical_taste == True:
print('and getting caught in the rain')
elif musical_taste == False:
print('You clearly have no taste in music')
你也可以使用提词器。
无耻地从README中截取:
#pip install prompter
from prompter import yesno
>>> yesno('Really?')
Really? [Y/n]
True
>>> yesno('Really?')
Really? [Y/n] no
False
>>> yesno('Really?', default='no')
Really? [y/N]
True