是否有任何简短的方法来实现APT(高级软件包工具)命令行界面在Python中的作用?
我的意思是,当包管理器提示后面是/否问题时[Yes/no],脚本接受YES/Y/yes/y或Enter(默认Yes为大写字母暗示).
我在官方文档找到的唯一的事情就是input和raw_input...
我知道这并不难以模仿,但重写是很烦人的:|
fma*_*ark 205
正如您所提到的,最简单的方法是使用raw_input()(或仅input()用于Python 3).没有内置的方法来做到这一点.来自食谱577058:
import sys
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = raw_input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
Run Code Online (Sandbox Code Playgroud)
用法示例:
>>> query_yes_no("Is cabbage yummier than cauliflower?")
Is cabbage yummier than cauliflower? [Y/n] oops
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [Y/n] [ENTER]
>>> True
>>> query_yes_no("Is cabbage yummier than cauliflower?", None)
Is cabbage yummier than cauliflower? [y/n] [ENTER]
Please respond with 'yes' or 'no' (or 'y' or 'n').
Is cabbage yummier than cauliflower? [y/n] y
>>> True
Run Code Online (Sandbox Code Playgroud)
Vic*_*ler 87
我这样做:
# raw_input returns the empty string for "enter"
yes = {'yes','y', 'ye', ''}
no = {'no','n'}
choice = raw_input().lower()
if choice in yes:
return True
elif choice in no:
return False
else:
sys.stdout.write("Please respond with 'yes' or 'no'")
Run Code Online (Sandbox Code Playgroud)
Ale*_*nko 48
strtoboolPython的标准库中有一个函数:http://docs.python.org/2/distutils/apiref.html?highlight = didutils.util #distutils.util.strtobool
您可以使用它来检查用户的输入并将其转换为True或False值.
Dan*_*gen 43
一个非常简单(但不是非常复杂)的方法是单一选择:
msg = 'Shall I?'
shall = input("%s (y/N) " % msg).lower() == 'y'
Run Code Online (Sandbox Code Playgroud)
您还可以编写一个简单的(略微改进的)函数:
def yn_choice(message, default='y'):
choices = 'Y/n' if default.lower() in ('y', 'yes') else 'y/N'
choice = input("%s (%s) " % (message, choices))
values = ('y', 'yes', '') if choices == 'Y/n' else ('y', 'yes')
return choice.strip().lower() in values
Run Code Online (Sandbox Code Playgroud)
注意:在Python 2上,使用raw_input而不是input.
Eya*_*vin 38
你可以使用click的confirm方法.
import click
if click.confirm('Do you want to continue?', default=True):
print('Do something')
Run Code Online (Sandbox Code Playgroud)
这将打印:
$ Do you want to continue? [Y/n]:
Run Code Online (Sandbox Code Playgroud)
应该适用Python 2/3于Linux,Mac或Windows.
文档:http://click.pocoo.org/5/prompts/#confirmation-prompts
jam*_*mes 21
正如@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')
#usage
>>> 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
Run Code Online (Sandbox Code Playgroud)
Dou*_*ams 15
我知道这已经回答了很多方法,这可能无法解决OP的具体问题(使用标准列表)但这是我为最常见的用例所做的,它比其他响应简单得多:
answer = input('Please indicate approval: [y/n]')
if not answer or answer[0].lower() != 'y':
print('You did not indicate approval')
exit(1)
Run Code Online (Sandbox Code Playgroud)
您也可以使用提示器.
无耻地从自述文件中获取:
#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
Run Code Online (Sandbox Code Playgroud)
我修改了fmark的答案,通过python 2/3兼容更多pythonic.
如果您对具有更多错误处理的内容感兴趣,请参阅ipython的实用程序模块
# PY2/3 compatibility
from __future__ import print_function
# You could use the six package for this
try:
input_ = raw_input
except NameError:
input_ = input
def query_yes_no(question, default=True):
"""Ask a yes/no question via standard input and return the answer.
If invalid input is given, the user will be asked until
they acutally give valid input.
Args:
question(str):
A question that is presented to the user.
default(bool|None):
The default value when enter is pressed with no value.
When None, there is no default value and the query
will loop.
Returns:
A bool indicating whether user has entered yes or no.
Side Effects:
Blocks program execution until valid input(y/n) is given.
"""
yes_list = ["yes", "y"]
no_list = ["no", "n"]
default_dict = { # default => prompt default string
None: "[y/n]",
True: "[Y/n]",
False: "[y/N]",
}
default_str = default_dict[default]
prompt_str = "%s %s " % (question, default_str)
while True:
choice = input_(prompt_str).lower()
if not choice and default is not None:
return default
if choice in yes_list:
return True
if choice in no_list:
return False
notification_str = "Please respond with 'y' or 'n'"
print(notification_str)
Run Code Online (Sandbox Code Playgroud)
对于 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")
Run Code Online (Sandbox Code Playgroud)
该strtobool()函数将字符串转换为布尔值。如果无法解析字符串,则会引发 ValueError。
在 Python 3raw_input()中已重命名为input().
正如 Geoff 所说,strtobool 实际上返回 0 或 1,因此结果必须转换为 bool。
这是 的实现strtobool,如果你想把特殊词识别为true,你可以复制代码并添加你自己的案例。
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")
Run Code Online (Sandbox Code Playgroud)
小智 5
在 2.7 上,这是否太非 Pythonic 了?
if raw_input('your prompt').lower()[0]=='y':
your code here
else:
alternate code here
Run Code Online (Sandbox Code Playgroud)
它至少捕获 Yes 的任何变化。
| 归档时间: |
|
| 查看次数: |
167388 次 |
| 最近记录: |