本文整理汇总了Python中sphinx.util.console.color_terminal函数的典型用法代码示例。如果您正苦于以下问题:Python color_terminal函数的具体用法?Python color_terminal怎么用?Python color_terminal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了color_terminal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main(argv):
if not color_terminal():
# Windows' poor cmd box doesn't understand ANSI sequences
nocolor()
try:
opts, args = getopt.getopt(argv[1:], "ab:t:d:c:CD:A:nNEqQWw:PThvj:", ["help", "version"])
allopts = set(opt[0] for opt in opts)
if "-h" in allopts or "--help" in allopts:
usage(argv)
print >> sys.stderr
print >> sys.stderr, "For more information, see " "<http://sphinx-doc.org/>."
return 0
if "--version" in allopts:
print "Sphinx (sphinx-build) %s" % __version__
return 0
srcdir = confdir = abspath(args[0])
if not path.isdir(srcdir):
print >> sys.stderr, "Error: Cannot find source directory `%s'." % (srcdir,)
return 1
if not path.isfile(path.join(srcdir, "conf.py")) and "-c" not in allopts and "-C" not in allopts:
print >> sys.stderr, ("Error: Source directory doesn't " "contain conf.py file.")
return 1
outdir = abspath(args[1])
except getopt.error, err:
usage(argv, "Error: %s" % err)
return 1
示例2: run
def run(self):
if not color_terminal():
# Windows' poor cmd box doesn't understand ANSI sequences
nocolor()
if not self.verbose:
status_stream = StringIO()
else:
status_stream = sys.stdout
confoverrides = {}
if self.project:
confoverrides['project'] = self.project
if self.version:
confoverrides['version'] = self.version
if self.release:
confoverrides['release'] = self.release
if self.today:
confoverrides['today'] = self.today
app = Sphinx(self.source_dir, self.config_dir,
self.builder_target_dir, self.doctree_dir,
self.builder, confoverrides, status_stream,
freshenv=self.fresh_env)
try:
app.build(force_all=self.all_files)
except Exception, err:
from docutils.utils import SystemMessage
if isinstance(err, SystemMessage):
print >>sys.stderr, darkred('reST markup error:')
print >>sys.stderr, err.args[0].encode('ascii',
'backslashreplace')
else:
raise
示例3: run
def run(self):
if not color_terminal():
# Windows' poor cmd box doesn't understand ANSI sequences
nocolor()
if not self.verbose:
status_stream = StringIO()
else:
status_stream = sys.stdout
app = Sphinx(self.source_dir, self.source_dir,
self.builder_target_dir, self.doctree_dir,
self.builder, {}, status_stream,
freshenv=self.fresh_env)
try:
if self.all_files:
app.builder.build_all()
else:
app.builder.build_update()
except Exception, err:
from docutils.utils import SystemMessage
if isinstance(err, SystemMessage):
sys.stderr, darkred('reST markup error:')
print >>sys.stderr, err.args[0].encode('ascii',
'backslashreplace')
else:
raise
示例4: main
def main(argv):
if not color_terminal():
# Windows' poor cmd box doesn't understand ANSI sequences
nocolor()
try:
opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:ng:NEqQWw:PThv',
['help', 'version'])
allopts = set(opt[0] for opt in opts)
if '-h' in allopts or '--help' in allopts:
usage(argv)
return 0
if '--version' in allopts:
print 'Sphinx (sphinx-build) %s' % __version__
return 0
srcdir = confdir = abspath(args[0])
if not path.isdir(srcdir):
print >>sys.stderr, 'Error: Cannot find source directory `%s\'.' % (
srcdir,)
return 1
if not path.isfile(path.join(srcdir, 'conf.py')) and \
'-c' not in allopts and '-C' not in allopts:
print >>sys.stderr, ('Error: Source directory doesn\'t '
'contain conf.py file.')
return 1
outdir = abspath(args[1])
if not path.isdir(outdir):
print >>sys.stderr, 'Making output directory...'
os.makedirs(outdir)
except getopt.error, err:
usage(argv, 'Error: %s' % err)
return 1
示例5: build_help
def build_help(self):
# type: () -> None
if not color_terminal():
nocolor()
print(bold("Sphinx v%s" % sphinx.__display_version__))
print("Please use `make %s' where %s is one of" % ((blue('target'),) * 2)) # type: ignore # NOQA
for osname, bname, description in BUILDERS:
if not osname or os.name == osname:
print(' %s %s' % (blue(bname.ljust(10)), description))
示例6: setup_logger
def setup_logger(verbose=1, color=True):
"""
Sets up and returns a Python Logger instance for the Sage
documentation builder. The optional argument sets logger's level
and message format.
"""
# Set up colors. Adapted from sphinx.cmdline.
import sphinx.util.console as c
if not color or not sys.stdout.isatty() or not c.color_terminal():
c.nocolor()
# Available colors: black, darkgray, (dark)red, dark(green),
# brown, yellow, (dark)blue, purple, fuchsia, turquoise, teal,
# lightgray, white. Available styles: reset, bold, faint,
# standout, underline, blink.
# Set up log record formats.
format_std = "%(message)s"
formatter = logging.Formatter(format_std)
# format_debug = "%(module)s #%(lineno)s %(funcName)s() %(message)s"
fields = ["%(module)s", "#%(lineno)s", "%(funcName)s()", "%(message)s"]
colors = ["darkblue", "darkred", "brown", "reset"]
styles = ["reset", "reset", "reset", "reset"]
format_debug = ""
for i in xrange(len(fields)):
format_debug += c.colorize(styles[i], c.colorize(colors[i], fields[i]))
if i != len(fields):
format_debug += " "
# Documentation: http://docs.python.org/library/logging.html
logger = logging.getLogger("doc.common.builder")
# Note: There's also Handler.setLevel(). The argument is the
# lowest severity message that the respective logger or handler
# will pass on. The default levels are DEBUG, INFO, WARNING,
# ERROR, and CRITICAL. We use "WARNING" for normal verbosity and
# "ERROR" for quiet operation. It's possible to define custom
# levels. See the documentation for details.
if verbose == 0:
logger.setLevel(logging.ERROR)
if verbose == 1:
logger.setLevel(logging.WARNING)
if verbose == 2:
logger.setLevel(logging.INFO)
if verbose == 3:
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(format_debug)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
示例7: main
def main(argv):
if not color_terminal():
# Windows' poor cmd box doesn't understand ANSI sequences
nocolor()
# parse options
try:
opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:nNEqQWw:PThvj:',
['help', 'version'])
except getopt.error, err:
usage(argv, 'Error: %s' % err)
return 1
示例8: ablog_start
def ablog_start(**kwargs):
if not color_terminal():
nocolor()
d = CONF_DEFAULTS
try:
ask_user(d)
except (KeyboardInterrupt, EOFError):
print('')
print('[Interrupted.]')
return
generate(d)
示例9: run
def run(self):
if not color_terminal():
nocolor()
if not self.verbose:
status_stream = StringIO()
else:
status_stream = sys.stdout
confoverrides = {}
if self.project:
confoverrides['project'] = self.project
if self.version:
confoverrides['version'] = self.version
if self.release:
confoverrides['release'] = self.release
if self.today:
confoverrides['today'] = self.today
if self.copyright:
confoverrides['copyright'] = self.copyright
app = Sphinx(self.source_dir, self.config_dir,
self.builder_target_dir, self.doctree_dir,
self.builder, confoverrides, status_stream,
freshenv=self.fresh_env,
warningiserror=self.warning_is_error)
try:
app.build(force_all=self.all_files)
if app.statuscode:
raise DistutilsExecError(
'caused by %s builder.' % app.builder.name)
except Exception as err:
if self.pdb:
import pdb
print(darkred('Exception occurred while building, starting debugger:'),
file=sys.stderr)
traceback.print_exc()
pdb.post_mortem(sys.exc_info()[2])
else:
from docutils.utils import SystemMessage
if isinstance(err, SystemMessage):
print(darkred('reST markup error:'), file=sys.stderr)
print(err.args[0].encode('ascii', 'backslashreplace'),
file=sys.stderr)
else:
raise
if self.link_index:
src = app.config.master_doc + app.builder.out_suffix
dst = app.builder.get_outfilename('index')
os.symlink(src, dst)
示例10: run
def run(self):
# type: () -> None
if not color_terminal():
nocolor()
if not self.verbose: # type: ignore
status_stream = StringIO()
else:
status_stream = sys.stdout # type: ignore
confoverrides = {} # type: Dict[str, Any]
if self.project:
confoverrides['project'] = self.project
if self.version:
confoverrides['version'] = self.version
if self.release:
confoverrides['release'] = self.release
if self.today:
confoverrides['today'] = self.today
if self.copyright:
confoverrides['copyright'] = self.copyright
if self.nitpicky:
confoverrides['nitpicky'] = self.nitpicky
for builder, builder_target_dir in self.builder_target_dirs:
app = None
try:
confdir = self.config_dir or self.source_dir
with patch_docutils(confdir), docutils_namespace():
app = Sphinx(self.source_dir, self.config_dir,
builder_target_dir, self.doctree_dir,
builder, confoverrides, status_stream,
freshenv=self.fresh_env,
warningiserror=self.warning_is_error)
app.build(force_all=self.all_files)
if app.statuscode:
raise DistutilsExecError(
'caused by %s builder.' % app.builder.name)
except Exception as exc:
handle_exception(app, self, exc, sys.stderr)
if not self.pdb:
raise SystemExit(1)
if not self.link_index:
continue
src = app.config.master_doc + app.builder.out_suffix # type: ignore
dst = app.builder.get_outfilename('index') # type: ignore
os.symlink(src, dst)
示例11: main
def main(argv=sys.argv):
if not color_terminal():
nocolor()
d = {}
if len(argv) > 3:
print 'Usage: sphinx-quickstart [root]'
sys.exit(1)
elif len(argv) == 2:
d['path'] = argv[1]
try:
ask_user(d)
except (KeyboardInterrupt, EOFError):
print
print '[Interrupted.]'
return
generate(d)
示例12: run
def run(self):
if not color_terminal():
nocolor()
if not self.verbose:
status_stream = StringIO()
else:
status_stream = sys.stdout
confoverrides = {}
if self.project:
confoverrides["project"] = self.project
if self.version:
confoverrides["version"] = self.version
if self.release:
confoverrides["release"] = self.release
if self.today:
confoverrides["today"] = self.today
if self.copyright:
confoverrides["copyright"] = self.copyright
try:
with docutils_namespace():
app = Sphinx(
self.source_dir,
self.config_dir,
self.builder_target_dir,
self.doctree_dir,
self.builder,
confoverrides,
status_stream,
freshenv=self.fresh_env,
warningiserror=self.warning_is_error,
)
app.build(force_all=self.all_files)
if app.statuscode:
raise DistutilsExecError("caused by %s builder." % app.builder.name)
except Exception as exc:
handle_exception(app, self, exc, sys.stderr)
if not self.pdb:
raise SystemExit(1)
if self.link_index:
src = app.config.master_doc + app.builder.out_suffix
dst = app.builder.get_outfilename("index")
os.symlink(src, dst)
示例13: main
def main(argv):
if not color_terminal():
# Windows' poor cmd box doesn't understand ANSI sequences
nocolor()
try:
opts, args = getopt.getopt(argv[1:], 'ab:t:d:c:CD:A:ng:NEqQWw:P')
allopts = set(opt[0] for opt in opts)
srcdir = confdir = path.abspath(args[0])
if not path.isdir(srcdir):
print >>sys.stderr, 'Error: Cannot find source directory.'
return 1
if not path.isfile(path.join(srcdir, 'conf.py')) and \
'-c' not in allopts and '-C' not in allopts:
print >>sys.stderr, ('Error: Source directory doesn\'t '
'contain conf.py file.')
return 1
outdir = path.abspath(args[1])
if not path.isdir(outdir):
print >>sys.stderr, 'Making output directory...'
os.makedirs(outdir)
except (IndexError, getopt.error):
usage(argv)
return 1
filenames = args[2:]
err = 0
for filename in filenames:
if not path.isfile(filename):
print >>sys.stderr, 'Cannot find file %r.' % filename
err = 1
if err:
return 1
buildername = None
force_all = freshenv = warningiserror = use_pdb = False
status = sys.stdout
warning = sys.stderr
error = sys.stderr
warnfile = None
confoverrides = {}
tags = []
doctreedir = path.join(outdir, '.doctrees')
for opt, val in opts:
if opt == '-b':
buildername = val
elif opt == '-a':
if filenames:
usage(argv, 'Cannot combine -a option and filenames.')
return 1
force_all = True
elif opt == '-t':
tags.append(val)
elif opt == '-d':
doctreedir = path.abspath(val)
elif opt == '-c':
confdir = path.abspath(val)
if not path.isfile(path.join(confdir, 'conf.py')):
print >>sys.stderr, ('Error: Configuration directory '
'doesn\'t contain conf.py file.')
return 1
elif opt == '-C':
confdir = None
elif opt == '-D':
try:
key, val = val.split('=')
except ValueError:
print >>sys.stderr, ('Error: -D option argument must be '
'in the form name=value.')
return 1
try:
val = int(val)
except ValueError:
pass
confoverrides[key] = val
elif opt == '-A':
try:
key, val = val.split('=')
except ValueError:
print >>sys.stderr, ('Error: -A option argument must be '
'in the form name=value.')
return 1
try:
val = int(val)
except ValueError:
pass
confoverrides['html_context.%s' % key] = val
elif opt == '-n':
confoverrides['nitpicky'] = True
elif opt == '-N':
nocolor()
elif opt == '-E':
freshenv = True
elif opt == '-q':
status = None
elif opt == '-Q':
status = None
warning = None
elif opt == '-W':
warningiserror = True
#.........这里部分代码省略.........
示例14: main
def main(argv=sys.argv[1:]):
# type: (List[str]) -> int
locale.setlocale(locale.LC_ALL, '')
sphinx.locale.init_console(os.path.join(package_dir, 'locale'), 'sphinx')
if not color_terminal():
nocolor()
# parse options
parser = get_parser()
try:
args = parser.parse_args(argv)
except SystemExit as err:
return err.code
d = vars(args)
# delete None or False value
d = dict((k, v) for k, v in d.items() if not (v is None or v is False))
try:
if 'quiet' in d:
if not set(['project', 'author']).issubset(d):
print(__('''"quiet" is specified, but any of "project" or \
"author" is not specified.'''))
return 1
if set(['quiet', 'project', 'author']).issubset(d):
# quiet mode with all required params satisfied, use default
d.setdefault('version', '')
d.setdefault('release', d['version'])
d2 = DEFAULTS.copy()
d2.update(d)
d = d2
if not valid_dir(d):
print()
print(bold(__('Error: specified path is not a directory, or sphinx'
' files already exist.')))
print(__('sphinx-quickstart only generate into a empty directory.'
' Please specify a new root path.'))
return 1
else:
ask_user(d)
except (KeyboardInterrupt, EOFError):
print()
print('[Interrupted.]')
return 130 # 128 + SIGINT
# decode values in d if value is a Python string literal
for key, value in d.items():
if isinstance(value, binary_type):
d[key] = term_decode(value)
# handle use of CSV-style extension values
d.setdefault('extensions', [])
for ext in d['extensions'][:]:
if ',' in ext:
d['extensions'].remove(ext)
d['extensions'].extend(ext.split(','))
for variable in d.get('variables', []):
try:
name, value = variable.split('=')
d[name] = value
except ValueError:
print(__('Invalid template variable: %s') % variable)
generate(d, templatedir=args.templatedir)
return 0
示例15: main
def main(argv=sys.argv[1:]): # type: ignore
# type: (List[unicode]) -> int
parser = get_parser()
# parse options
try:
args = parser.parse_args(argv)
except SystemExit as err:
return err.code
# get paths (first and second positional argument)
try:
srcdir = abspath(args.sourcedir)
confdir = abspath(args.confdir or srcdir)
if args.noconfig:
confdir = None
if not path.isdir(srcdir):
print('Error: Cannot find source directory `%s\'.' % srcdir,
file=sys.stderr)
return 1
if not args.noconfig and not path.isfile(path.join(confdir, 'conf.py')):
print('Error: Config directory doesn\'t contain a conf.py file.',
file=sys.stderr)
return 1
outdir = abspath(args.outputdir)
if srcdir == outdir:
print('Error: source directory and destination directory are same.',
file=sys.stderr)
return 1
except UnicodeError:
print(
'Error: Multibyte filename not supported on this filesystem '
'encoding (%r).' % fs_encoding, file=sys.stderr)
return 1
# handle remaining filename arguments
filenames = args.filenames
errored = False
for filename in filenames:
if not path.isfile(filename):
print('Error: Cannot find file %r.' % filename, file=sys.stderr)
errored = True
if errored:
return 1
# likely encoding used for command-line arguments
try:
locale = __import__('locale') # due to submodule of the same name
likely_encoding = locale.getpreferredencoding()
except Exception:
likely_encoding = None
if args.force_all and filenames:
print('Error: Cannot combine -a option and filenames.', file=sys.stderr)
return 1
if args.color == 'no' or (args.color == 'auto' and not color_terminal()):
nocolor()
doctreedir = abspath(args.doctreedir or path.join(outdir, '.doctrees'))
status = sys.stdout
warning = sys.stderr
error = sys.stderr
if args.quiet:
status = None
if args.really_quiet:
status = warning = None
if warning and args.warnfile:
try:
warnfp = open(args.warnfile, 'w')
except Exception as exc:
print('Error: Cannot open warning file %r: %s' %
(args.warnfile, exc), file=sys.stderr)
sys.exit(1)
warning = Tee(warning, warnfp) # type: ignore
error = warning
confoverrides = {}
for val in args.define:
try:
key, val = val.split('=', 1)
except ValueError:
print('Error: -D option argument must be in the form name=value.',
file=sys.stderr)
return 1
if likely_encoding and isinstance(val, binary_type):
try:
val = val.decode(likely_encoding)
except UnicodeError:
pass
confoverrides[key] = val
for val in args.htmldefine:
try:
key, val = val.split('=')
except ValueError:
print('Error: -A option argument must be in the form name=value.',
file=sys.stderr)
#.........这里部分代码省略.........