本文整理汇总了Python中nikola.utils.ask函数的典型用法代码示例。如果您正苦于以下问题:Python ask函数的具体用法?Python ask怎么用?Python ask使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ask函数的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: chandler
def chandler(default, toconf):
print(
"You can configure comments now. Type '?' (a question mark, sans quotes) to list available comment systems. If you do not want any comments, just leave the field blank."
)
answer = ask("Comment system", "")
while answer.strip() == "?":
print("\n# Available comment systems:")
print(SAMPLE_CONF["_SUPPORTED_COMMENT_SYSTEMS"])
print("")
answer = ask("Comment system", "")
while answer and answer not in LEGAL_VALUES["COMMENT_SYSTEM"]:
if answer != "?":
print(" ERROR: Nikola does not know this comment system.")
print("\n# Available comment systems:")
print(SAMPLE_CONF["_SUPPORTED_COMMENT_SYSTEMS"])
print("")
answer = ask("Comment system", "")
SAMPLE_CONF["COMMENT_SYSTEM"] = answer
SAMPLE_CONF["COMMENT_SYSTEM_ID"] = ""
if answer:
print(
"You need to provide the site identifier for your comment system. Consult the Nikola manual for details on what the value should be. (you can leave it empty and come back later)"
)
answer = ask("Comment system site identifier", "")
SAMPLE_CONF["COMMENT_SYSTEM_ID"] = answer
示例2: lhandler
def lhandler(default, toconf, show_header=True):
if show_header:
print("We will now ask you to provide the list of languages you want to use.")
print(
"Please list all the desired languages, comma-separated, using ISO 639-1 codes. The first language will be used as the default."
)
print("Type '?' (a question mark, sans quotes) to list available languages.")
answer = ask("Language(s) to use", "en")
while answer.strip() == "?":
print("\n# Available languages:")
try:
print(SAMPLE_CONF["_SUPPORTED_LANGUAGES"] + "\n")
except UnicodeEncodeError:
# avoid Unicode characters in supported language names
print(unidecode.unidecode(SAMPLE_CONF["_SUPPORTED_LANGUAGES"]) + "\n")
answer = ask("Language(s) to use", "en")
langs = [i.strip().lower().replace("-", "_") for i in answer.split(",")]
for partial, full in LEGAL_VALUES["_TRANSLATIONS_WITH_COUNTRY_SPECIFIERS"].items():
if partial in langs:
langs[langs.index(partial)] = full
print("NOTICE: Assuming '{0}' instead of '{1}'.".format(full, partial))
default = langs.pop(0)
SAMPLE_CONF["DEFAULT_LANG"] = default
# format_default_translations_config() is intelligent enough to
# return the current value if there are no additional languages.
SAMPLE_CONF["TRANSLATIONS"] = format_default_translations_config(langs)
# Get messages for navigation_links. In order to do this, we need
# to generate a throwaway TRANSLATIONS dict.
tr = {default: ""}
for l in langs:
tr[l] = "./" + l
# Assuming that base contains all the locales, and that base does
# not inherit from anywhere.
try:
messages = load_messages(["base"], tr, default)
SAMPLE_CONF["NAVIGATION_LINKS"] = format_navigation_links(
langs, default, messages, SAMPLE_CONF["STRIP_INDEXES"]
)
except nikola.utils.LanguageNotFoundError as e:
print(" ERROR: the language '{0}' is not supported.".format(e.lang))
print(
" Are you sure you spelled the name correctly? Names are case-sensitive and need to be reproduced as-is (complete with the country specifier, if any)."
)
print("\nType '?' (a question mark, sans quotes) to list available languages.")
lhandler(default, toconf, show_header=False)
示例3: tzhandler
def tzhandler(default, toconf):
print("\nPlease choose the correct time zone for your blog. Nikola uses the tz database.")
print("You can find your time zone here:")
print("https://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
print("")
answered = False
while not answered:
try:
lz = get_localzone()
except:
lz = None
answer = ask("Time zone", lz if lz else "UTC")
tz = dateutil.tz.gettz(answer)
if tz is None:
print(" WARNING: Time zone not found. Searching list of time zones for a match.")
zonesfile = tarfile.open(fileobj=dateutil.zoneinfo.getzoneinfofile_stream())
zonenames = [zone for zone in zonesfile.getnames() if answer.lower() in zone.lower()]
if len(zonenames) == 1:
tz = dateutil.tz.gettz(zonenames[0])
answer = zonenames[0]
print(" Picking '{0}'.".format(answer))
elif len(zonenames) > 1:
print(" The following time zones match your query:")
print(" " + "\n ".join(zonenames))
continue
if tz is not None:
time = datetime.datetime.now(tz).strftime("%H:%M:%S")
print(" Current time in {0}: {1}".format(answer, time))
answered = ask_yesno("Use this time zone?", True)
else:
print(" ERROR: No matches found. Please try again.")
SAMPLE_CONF["TIMEZONE"] = answer
示例4: urlhandler
def urlhandler(default, toconf):
answer = ask("Site URL", "https://example.com/")
try:
answer = answer.decode("utf-8")
except (AttributeError, UnicodeDecodeError):
pass
if not answer.startswith("http"):
print(" ERROR: You must specify a protocol (http or https).")
urlhandler(default, toconf)
return
if not answer.endswith("/"):
print(" The URL does not end in '/' -- adding it.")
answer += "/"
dst_url = urlsplit(answer)
try:
dst_url.netloc.encode("ascii")
except (UnicodeEncodeError, UnicodeDecodeError):
# The IDN contains characters beyond ASCII. We must convert it
# to Punycode. (Issue #1644)
nl = dst_url.netloc.encode("idna")
answer = urlunsplit((dst_url.scheme, nl, dst_url.path, dst_url.query, dst_url.fragment))
print(" Converting to Punycode:", answer)
SAMPLE_CONF["SITE_URL"] = answer
示例5: tzhandler
def tzhandler(default, toconf):
print("\nPlease choose the correct time zone for your blog. Nikola uses the tz database.")
print("You can find your time zone here:")
print("http://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
print("")
answered = False
while not answered:
try:
lz = get_localzone()
except:
lz = None
answer = ask('Time zone', lz if lz else "UTC")
tz = dateutil.tz.gettz(answer)
if tz is None:
print(" WARNING: Time zone not found. Searching most common timezones for a match.")
zonesfile = tarfile.TarFile.open(os.path.join(dateutil.zoneinfo.ZONEINFOFILE))
zonenames = [zone for zone in zonesfile.getnames() if answer.lower() in zone.lower()]
if len(zonenames) == 1:
tz = dateutil.tz.gettz(zonenames[0])
elif len(zonenames) > 1:
print(" Could not pick one timezone. Choose one of the following:")
print(' ' + '\n '.join(zonenames))
continue
if tz is not None:
time = datetime.datetime.now(tz).strftime('%H:%M:%S')
print(" Current time in {0}: {1}".format(answer, time))
answered = ask_yesno("Use this time zone?", True)
else:
print(" ERROR: Time zone not found. Please try again. Time zones are case-sensitive.")
SAMPLE_CONF['TIMEZONE'] = answer
示例6: tzhandler
def tzhandler(default, toconf):
print("\nPlease choose the correct time zone for your blog. Nikola uses the tz database.")
print("You can find your time zone here:")
print("http://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
print("")
answered = False
while not answered:
answer = ask("Time zone", "UTC")
tz = dateutil.tz.gettz(answer)
if tz is not None:
time = datetime.datetime.now(tz).strftime("%H:%M:%S")
print(" Current time in {0}: {1}".format(answer, time))
answered = ask_yesno("Use this time zone?", True)
else:
print(" ERROR: Time zone not found. Please try again. Time zones are case-sensitive.")
SAMPLE_CONF["TIMEZONE"] = answer
示例7: _execute
def _execute(self, options, args):
"""Create a new post or page."""
global LOGGER
compiler_names = [p.name for p in
self.site.plugin_manager.getPluginsOfCategory(
"PageCompiler")]
if len(args) > 1:
print(self.help())
return False
elif args:
path = args[0]
else:
path = None
# Even though stuff was split into `new_page`, it’s easier to do it
# here not to duplicate the code.
is_page = options.get('is_page', False)
is_post = not is_page
content_type = 'page' if is_page else 'post'
title = options['title'] or None
author = options['author'] or ''
tags = options['tags']
onefile = options['onefile']
twofile = options['twofile']
import_file = options['import']
if is_page:
LOGGER = PAGELOGGER
else:
LOGGER = POSTLOGGER
if twofile:
onefile = False
if not onefile and not twofile:
onefile = self.site.config.get('ONE_FILE_POSTS', True)
content_format = options['content_format']
if not content_format: # Issue #400
content_format = get_default_compiler(
is_post,
self.site.config['COMPILERS'],
self.site.config['post_pages'])
if content_format not in compiler_names:
LOGGER.error("Unknown {0} format {1}".format(content_type, content_format))
return
compiler_plugin = self.site.plugin_manager.getPluginByName(
content_format, "PageCompiler").plugin_object
# Guess where we should put this
entry = filter_post_pages(content_format, is_post,
self.site.config['COMPILERS'],
self.site.config['post_pages'])
if import_file:
print("Importing Existing {xx}".format(xx=content_type.title()))
print("-----------------------\n")
else:
print("Creating New {xx}".format(xx=content_type.title()))
print("-----------------\n")
if title is not None:
print("Title:", title)
else:
while not title:
title = utils.ask('Title')
if isinstance(title, utils.bytes_str):
try:
title = title.decode(sys.stdin.encoding)
except (AttributeError, TypeError): # for tests
title = title.decode('utf-8')
title = title.strip()
if not path:
slug = utils.slugify(title)
else:
if isinstance(path, utils.bytes_str):
try:
path = path.decode(sys.stdin.encoding)
except (AttributeError, TypeError): # for tests
path = path.decode('utf-8')
slug = utils.slugify(os.path.splitext(os.path.basename(path))[0])
if isinstance(author, utils.bytes_str):
try:
author = author.decode(sys.stdin.encoding)
except (AttributeError, TypeError): # for tests
author = author.decode('utf-8')
# Calculate the date to use for the content
schedule = options['schedule'] or self.site.config['SCHEDULE_ALL']
rule = self.site.config['SCHEDULE_RULE']
self.site.scan_posts()
timeline = self.site.timeline
last_date = None if not timeline else timeline[0].date
date = get_date(schedule, rule, last_date, self.site.tzinfo, self.site.config['FORCE_ISO8601'])
data = {
'title': title,
#.........这里部分代码省略.........
示例8: ask_questions
def ask_questions(target):
"""Ask some questions about Nikola."""
def urlhandler(default, toconf):
answer = ask("Site URL", "https://example.com/")
try:
answer = answer.decode("utf-8")
except (AttributeError, UnicodeDecodeError):
pass
if not answer.startswith("http"):
print(" ERROR: You must specify a protocol (http or https).")
urlhandler(default, toconf)
return
if not answer.endswith("/"):
print(" The URL does not end in '/' -- adding it.")
answer += "/"
dst_url = urlsplit(answer)
try:
dst_url.netloc.encode("ascii")
except (UnicodeEncodeError, UnicodeDecodeError):
# The IDN contains characters beyond ASCII. We must convert it
# to Punycode. (Issue #1644)
nl = dst_url.netloc.encode("idna")
answer = urlunsplit((dst_url.scheme, nl, dst_url.path, dst_url.query, dst_url.fragment))
print(" Converting to Punycode:", answer)
SAMPLE_CONF["SITE_URL"] = answer
def prettyhandler(default, toconf):
SAMPLE_CONF["PRETTY_URLS"] = ask_yesno(
"Enable pretty URLs (/page/ instead of /page.html) that don't need web server configuration?",
default=True,
)
SAMPLE_CONF["STRIP_INDEXES"] = SAMPLE_CONF["PRETTY_URLS"]
def lhandler(default, toconf, show_header=True):
if show_header:
print("We will now ask you to provide the list of languages you want to use.")
print(
"Please list all the desired languages, comma-separated, using ISO 639-1 codes. The first language will be used as the default."
)
print("Type '?' (a question mark, sans quotes) to list available languages.")
answer = ask("Language(s) to use", "en")
while answer.strip() == "?":
print("\n# Available languages:")
try:
print(SAMPLE_CONF["_SUPPORTED_LANGUAGES"] + "\n")
except UnicodeEncodeError:
# avoid Unicode characters in supported language names
print(unidecode.unidecode(SAMPLE_CONF["_SUPPORTED_LANGUAGES"]) + "\n")
answer = ask("Language(s) to use", "en")
langs = [i.strip().lower().replace("-", "_") for i in answer.split(",")]
for partial, full in LEGAL_VALUES["_TRANSLATIONS_WITH_COUNTRY_SPECIFIERS"].items():
if partial in langs:
langs[langs.index(partial)] = full
print("NOTICE: Assuming '{0}' instead of '{1}'.".format(full, partial))
default = langs.pop(0)
SAMPLE_CONF["DEFAULT_LANG"] = default
# format_default_translations_config() is intelligent enough to
# return the current value if there are no additional languages.
SAMPLE_CONF["TRANSLATIONS"] = format_default_translations_config(langs)
# Get messages for navigation_links. In order to do this, we need
# to generate a throwaway TRANSLATIONS dict.
tr = {default: ""}
for l in langs:
tr[l] = "./" + l
# Assuming that base contains all the locales, and that base does
# not inherit from anywhere.
try:
messages = load_messages(["base"], tr, default)
SAMPLE_CONF["NAVIGATION_LINKS"] = format_navigation_links(
langs, default, messages, SAMPLE_CONF["STRIP_INDEXES"]
)
except nikola.utils.LanguageNotFoundError as e:
print(" ERROR: the language '{0}' is not supported.".format(e.lang))
print(
" Are you sure you spelled the name correctly? Names are case-sensitive and need to be reproduced as-is (complete with the country specifier, if any)."
)
print("\nType '?' (a question mark, sans quotes) to list available languages.")
lhandler(default, toconf, show_header=False)
def tzhandler(default, toconf):
print("\nPlease choose the correct time zone for your blog. Nikola uses the tz database.")
print("You can find your time zone here:")
print("https://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
print("")
answered = False
while not answered:
try:
lz = get_localzone()
except:
lz = None
answer = ask("Time zone", lz if lz else "UTC")
tz = dateutil.tz.gettz(answer)
if tz is None:
#.........这里部分代码省略.........
示例9: ask_questions
def ask_questions(target):
"""Ask some questions about Nikola."""
def lhandler(default, toconf, show_header=True):
if show_header:
print("We will now ask you to provide the list of languages you want to use.")
print("Please list all the desired languages, comma-separated, using ISO 639-1 codes. The first language will be used as the default.")
print("Type '?' (a question mark, sans quotes) to list available languages.")
answer = ask('Language(s) to use', 'en')
while answer.strip() == '?':
print('\n# Available languages:')
try:
print(SAMPLE_CONF['_SUPPORTED_LANGUAGES'] + '\n')
except UnicodeEncodeError:
# avoid Unicode characters in supported language names
print(unidecode.unidecode(SAMPLE_CONF['_SUPPORTED_LANGUAGES']) + '\n')
answer = ask('Language(s) to use', 'en')
langs = [i.strip().lower().replace('-', '_') for i in answer.split(',')]
for partial, full in LEGAL_VALUES['_TRANSLATIONS_WITH_COUNTRY_SPECIFIERS'].items():
if partial in langs:
langs[langs.index(partial)] = full
print("NOTICE: Assuming '{0}' instead of '{1}'.".format(full, partial))
default = langs.pop(0)
SAMPLE_CONF['DEFAULT_LANG'] = default
# format_default_translations_config() is intelligent enough to
# return the current value if there are no additional languages.
SAMPLE_CONF['TRANSLATIONS'] = format_default_translations_config(langs)
# Get messages for navigation_links. In order to do this, we need
# to generate a throwaway TRANSLATIONS dict.
tr = {default: ''}
for l in langs:
tr[l] = './' + l
# Assuming that base contains all the locales, and that base does
# not inherit from anywhere.
try:
messages = load_messages(['base'], tr, default)
SAMPLE_CONF['NAVIGATION_LINKS'] = format_navigation_links(langs, default, messages)
except nikola.utils.LanguageNotFoundError as e:
print(" ERROR: the language '{0}' is not supported.".format(e.lang))
print(" Are you sure you spelled the name correctly? Names are case-sensitive and need to be reproduced as-is (complete with the country specifier, if any).")
print("\nType '?' (a question mark, sans quotes) to list available languages.")
lhandler(default, toconf, show_header=False)
def tzhandler(default, toconf):
print("\nPlease choose the correct time zone for your blog. Nikola uses the tz database.")
print("You can find your time zone here:")
print("http://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
print("")
answered = False
while not answered:
try:
lz = get_localzone()
except:
lz = None
answer = ask('Time zone', lz if lz else "UTC")
tz = dateutil.tz.gettz(answer)
if tz is None:
print(" WARNING: Time zone not found. Searching list of time zones for a match.")
zonesfile = tarfile.open(fileobj=dateutil.zoneinfo.getzoneinfofile_stream())
zonenames = [zone for zone in zonesfile.getnames() if answer.lower() in zone.lower()]
if len(zonenames) == 1:
tz = dateutil.tz.gettz(zonenames[0])
answer = zonenames[0]
print(" Picking '{0}'.".format(answer))
elif len(zonenames) > 1:
print(" The following time zones match your query:")
print(' ' + '\n '.join(zonenames))
continue
if tz is not None:
time = datetime.datetime.now(tz).strftime('%H:%M:%S')
print(" Current time in {0}: {1}".format(answer, time))
answered = ask_yesno("Use this time zone?", True)
else:
print(" ERROR: No matches found. Please try again.")
SAMPLE_CONF['TIMEZONE'] = answer
def chandler(default, toconf):
print("You can configure comments now. Type '?' (a question mark, sans quotes) to list available comment systems. If you do not want any comments, just leave the field blank.")
answer = ask('Comment system', '')
while answer.strip() == '?':
print('\n# Available comment systems:')
print(SAMPLE_CONF['_SUPPORTED_COMMENT_SYSTEMS'])
print('')
answer = ask('Comment system', '')
while answer and answer not in LEGAL_VALUES['COMMENT_SYSTEM']:
if answer != '?':
print(' ERROR: Nikola does not know this comment system.')
print('\n# Available comment systems:')
print(SAMPLE_CONF['_SUPPORTED_COMMENT_SYSTEMS'])
print('')
answer = ask('Comment system', '')
SAMPLE_CONF['COMMENT_SYSTEM'] = answer
SAMPLE_CONF['COMMENT_SYSTEM_ID'] = ''
#.........这里部分代码省略.........
示例10: _execute
def _execute(self, options, args):
"""Create a new post or page."""
global LOGGER
compiler_names = [p.name for p in
self.site.plugin_manager.getPluginsOfCategory(
"PageCompiler")]
if len(args) > 1:
print(self.help())
return False
elif args:
path = args[0]
else:
path = None
# Even though stuff was split into `new_page`, it’s easier to do it
# here not to duplicate the code.
is_page = options.get('is_page', False)
is_post = not is_page
content_type = 'page' if is_page else 'post'
title = options['title'] or None
author = options['author'] or ''
tags = options['tags']
onefile = options['onefile']
twofile = options['twofile']
import_file = options['import']
wants_available = options['available-formats']
date_path_opt = options['date-path']
date_path_auto = self.site.config['NEW_POST_DATE_PATH']
date_path_format = self.site.config['NEW_POST_DATE_PATH_FORMAT'].strip('/')
if wants_available:
self.print_compilers()
return
if is_page:
LOGGER = PAGELOGGER
else:
LOGGER = POSTLOGGER
if twofile:
onefile = False
if not onefile and not twofile:
onefile = self.site.config.get('ONE_FILE_POSTS', True)
content_format = options['content_format']
content_subformat = None
if "@" in content_format:
content_format, content_subformat = content_format.split("@")
if not content_format: # Issue #400
content_format = get_default_compiler(
is_post,
self.site.config['COMPILERS'],
self.site.config['post_pages'])
if content_format not in compiler_names:
LOGGER.error("Unknown {0} format {1}, maybe you need to install a plugin or enable an existing one?".format(content_type, content_format))
self.print_compilers()
return
compiler_plugin = self.site.plugin_manager.getPluginByName(
content_format, "PageCompiler").plugin_object
# Guess where we should put this
entry = self.filter_post_pages(content_format, is_post)
if entry is False:
return 1
if import_file:
print("Importing Existing {xx}".format(xx=content_type.title()))
print("-----------------------\n")
else:
print("Creating New {xx}".format(xx=content_type.title()))
print("-----------------\n")
if title is not None:
print("Title:", title)
else:
while not title:
title = utils.ask('Title')
if isinstance(title, utils.bytes_str):
try:
title = title.decode(sys.stdin.encoding)
except (AttributeError, TypeError): # for tests
title = title.decode('utf-8')
title = title.strip()
if not path:
slug = utils.slugify(title, lang=self.site.default_lang)
else:
if isinstance(path, utils.bytes_str):
try:
path = path.decode(sys.stdin.encoding)
except (AttributeError, TypeError): # for tests
path = path.decode('utf-8')
slug = utils.slugify(os.path.splitext(os.path.basename(path))[0], lang=self.site.default_lang)
if isinstance(author, utils.bytes_str):
#.........这里部分代码省略.........
示例11: _execute
def _execute(self, options, args):
"""Create a new post or page."""
global LOGGER
compiler_names = [p.name for p in self.site.plugin_manager.getPluginsOfCategory("PageCompiler")]
if len(args) > 1:
print(self.help())
return False
elif args:
path = args[0]
else:
path = None
# Even though stuff was split into `new_page`, it’s easier to do it
# here not to duplicate the code.
is_page = options.get("is_page", False)
is_post = not is_page
content_type = "page" if is_page else "post"
title = options["title"] or None
author = options["author"] or ""
tags = options["tags"]
onefile = options["onefile"]
twofile = options["twofile"]
import_file = options["import"]
wants_available = options["available-formats"]
if wants_available:
self.print_compilers()
return
if is_page:
LOGGER = PAGELOGGER
else:
LOGGER = POSTLOGGER
if twofile:
onefile = False
if not onefile and not twofile:
onefile = self.site.config.get("ONE_FILE_POSTS", True)
content_format = options["content_format"]
content_subformat = None
if "@" in content_format:
content_format, content_subformat = content_format.split("@")
if not content_format: # Issue #400
content_format = get_default_compiler(
is_post, self.site.config["COMPILERS"], self.site.config["post_pages"]
)
if content_format not in compiler_names:
LOGGER.error(
"Unknown {0} format {1}, maybe you need to install a plugin?".format(content_type, content_format)
)
self.print_compilers()
return
compiler_plugin = self.site.plugin_manager.getPluginByName(content_format, "PageCompiler").plugin_object
# Guess where we should put this
entry = self.filter_post_pages(content_format, is_post)
if entry is False:
return 1
if import_file:
print("Importing Existing {xx}".format(xx=content_type.title()))
print("-----------------------\n")
else:
print("Creating New {xx}".format(xx=content_type.title()))
print("-----------------\n")
if title is not None:
print("Title:", title)
else:
while not title:
title = utils.ask("Title")
if isinstance(title, utils.bytes_str):
try:
title = title.decode(sys.stdin.encoding)
except (AttributeError, TypeError): # for tests
title = title.decode("utf-8")
title = title.strip()
if not path:
slug = utils.slugify(title)
else:
if isinstance(path, utils.bytes_str):
try:
path = path.decode(sys.stdin.encoding)
except (AttributeError, TypeError): # for tests
path = path.decode("utf-8")
slug = utils.slugify(os.path.splitext(os.path.basename(path))[0])
if isinstance(author, utils.bytes_str):
try:
author = author.decode(sys.stdin.encoding)
except (AttributeError, TypeError): # for tests
author = author.decode("utf-8")
#.........这里部分代码省略.........
示例12: ask_questions
def ask_questions(target):
"""Ask some questions about Nikola."""
def lhandler(default, toconf, show_header=True):
if show_header:
print("We will now ask you to provide the list of languages you want to use.")
print(
"Please list all the desired languages, comma-separated, using ISO 639-1 codes. The first language will be used as the default."
)
print("Type '?' (a question mark, sans quotes) to list available languages.")
answer = ask("Language(s) to use", "en")
while answer.strip() == "?":
print("\n# Available languages:")
print(SAMPLE_CONF["_SUPPORTED_LANGUAGES"] + "\n")
answer = ask("Language(s) to use", "en")
langs = [i.strip().lower().replace("-", "_") for i in answer.split(",")]
for partial, full in LEGAL_VALUES["_TRANSLATIONS_WITH_COUNTRY_SPECIFIERS"].items():
if partial in langs:
langs[langs.index(partial)] = full
print("NOTICE: Assuming '{0}' instead of '{1}'.".format(full, partial))
default = langs.pop(0)
SAMPLE_CONF["DEFAULT_LANG"] = default
# format_default_translations_config() is intelligent enough to
# return the current value if there are no additional languages.
SAMPLE_CONF["TRANSLATIONS"] = format_default_translations_config(langs)
# Get messages for navigation_links. In order to do this, we need
# to generate a throwaway TRANSLATIONS dict.
tr = {default: ""}
for l in langs:
tr[l] = "./" + l
# Assuming that base contains all the locales, and that base does
# not inherit from anywhere.
try:
messages = load_messages(["base"], tr, default)
SAMPLE_CONF["NAVIGATION_LINKS"] = format_navigation_links(langs, default, messages)
except nikola.utils.LanguageNotFoundError as e:
print(" ERROR: the language '{0}' is not supported.".format(e.lang))
print(
" Are you sure you spelled the name correctly? Names are case-sensitive and need to be reproduced as-is (complete with the country specifier, if any)."
)
print("\nType '?' (a question mark, sans quotes) to list available languages.")
lhandler(default, toconf, show_header=False)
def tzhandler(default, toconf):
print("\nPlease choose the correct time zone for your blog. Nikola uses the tz database.")
print("You can find your time zone here:")
print("http://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
print("")
answered = False
while not answered:
answer = ask("Time zone", "UTC")
tz = dateutil.tz.gettz(answer)
if tz is not None:
time = datetime.datetime.now(tz).strftime("%H:%M:%S")
print(" Current time in {0}: {1}".format(answer, time))
answered = ask_yesno("Use this time zone?", True)
else:
print(" ERROR: Time zone not found. Please try again. Time zones are case-sensitive.")
SAMPLE_CONF["TIMEZONE"] = answer
def chandler(default, toconf):
print(
"You can configure comments now. Type '?' (a question mark, sans quotes) to list available comment systems. If you do not want any comments, just leave the field blank."
)
answer = ask("Comment system", "")
while answer.strip() == "?":
print("\n# Available comment systems:")
print(SAMPLE_CONF["_SUPPORTED_COMMENT_SYSTEMS"])
print("")
answer = ask("Comment system", "")
while answer and answer not in LEGAL_VALUES["COMMENT_SYSTEM"]:
if answer != "?":
print(" ERROR: Nikola does not know this comment system.")
print("\n# Available comment systems:")
print(SAMPLE_CONF["_SUPPORTED_COMMENT_SYSTEMS"])
print("")
answer = ask("Comment system", "")
SAMPLE_CONF["COMMENT_SYSTEM"] = answer
SAMPLE_CONF["COMMENT_SYSTEM_ID"] = ""
if answer:
print(
"You need to provide the site identifier for your comment system. Consult the Nikola manual for details on what the value should be. (you can leave it empty and come back later)"
)
answer = ask("Comment system site identifier", "")
SAMPLE_CONF["COMMENT_SYSTEM_ID"] = answer
STORAGE = {"target": target}
questions = [
("Questions about the site", None, None, None),
# query, default, toconf, destination
("Destination", None, False, "!target"),
("Site title", "My Nikola Site", True, "BLOG_TITLE"),
#.........这里部分代码省略.........