有没有什么简单的方法来实现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…
我知道模仿它并不难,但是重写:|很烦人
当前回答
我知道这已经被回答了很多方法,这可能不能回答OP的具体问题(标准列表),但这是我为最常见的用例所做的,它比其他回答简单得多:
answer = input('Please indicate approval: [y/n]')
if not answer or answer[0].lower() != 'y':
print('You did not indicate approval')
exit(1)
其他回答
对于Python 3,我使用这个函数:
def user_prompt(question: str) -> bool:
""" Prompt the yes/no-*question* to the user. """
from distutils.util import strtobool
while True:
user_input = input(question + " [y/n]: ")
try:
return bool(strtobool(user_input))
except ValueError:
print("Please use y/n or yes/no.\n")
函数的作用是:将字符串转换为bool类型。如果字符串不能被解析,它将引发ValueError。
在Python 3中,raw_input()已重命名为input()。
正如Geoff所说,strtoool实际上返回0或1,因此结果必须转换为bool类型。
这是strtobool的实现,如果你想让特殊的单词被识别为true,你可以复制代码并添加自己的case。
def strtobool (val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))
Python x.x
res = True
while res:
res = input("Please confirm with y/yes...").lower(); res = res not in {'y','yes','Y','YES',''}
正如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
这个怎么样:
def yes(prompt = 'Please enter Yes/No: '):
while True:
try:
i = raw_input(prompt)
except KeyboardInterrupt:
return False
if i.lower() in ('yes','y'): return True
elif i.lower() in ('no','n'): return False
您可以使用单击的确认方法。
import click
if click.confirm('Do you want to continue?', default=True):
print('Do something')
这将打印:
$ Do you want to continue? [Y/n]:
应该适用于Linux, Mac或Windows上的Python 2/3。
文档:http://click.pocoo.org/5/prompts/ # confirmation-prompts