本文整理汇总了Python中sphinx.util.console.color_terminal函数的典型用法代码示例。如果您正苦于以下问题:Python color_terminal函数的具体用法?Python color_terminal怎么用?Python color_terminal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了color_terminal函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:cumtjie,项目名称:commcarehq-venv,代码行数:27,代码来源:cmdline.py
示例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
开发者ID:SurfasJones,项目名称:icecream-info,代码行数:32,代码来源:setup_command.py
示例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
开发者ID:89sos98,项目名称:main,代码行数:26,代码来源:setup_command.py
示例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
开发者ID:solanolabs,项目名称:sphinx,代码行数:32,代码来源:cmdline.py
示例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))
开发者ID:lmregus,项目名称:Portfolio,代码行数:10,代码来源:make_mode.py
示例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
开发者ID:jtmurphy89,项目名称:sagelib,代码行数:54,代码来源:builder.py
示例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
开发者ID:Scalr,项目名称:sphinx,代码行数:12,代码来源:cmdline.py
示例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)
开发者ID:abakan,项目名称:ablog,代码行数:14,代码来源:start.py
示例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)
开发者ID:LeoHuckvale,项目名称:sphinx,代码行数:49,代码来源:setup_command.py
示例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)
开发者ID:olivier-heurtier,项目名称:sphinx,代码行数:48,代码来源:setup_command.py
示例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)
开发者ID:certik,项目名称:sphinx,代码行数:17,代码来源:quickstart.py
示例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)
开发者ID:TimKam,项目名称:sphinx,代码行数:44,代码来源:setup_command.py
示例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
#.........这里部分代码省略.........
开发者ID:hurtado452,项目名称:battleAtSea-master,代码行数:101,代码来源:cmdline.py
示例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
开发者ID:AWhetter,项目名称:sphinx,代码行数:69,代码来源:quickstart.py
示例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)
#.........这里部分代码省略.........
开发者ID:LFYG,项目名称:sphinx,代码行数:101,代码来源:cmdline.py
示例16: main
def main(argv):
if not color_terminal():
nocolor()
parser = optparse.OptionParser(USAGE, epilog=EPILOG, formatter=MyFormatter())
parser.add_option('--version', action='store_true', dest='version',
help='show version information and exit')
group = parser.add_option_group('General options')
group.add_option('-b', metavar='BUILDER', dest='builder', default='html',
help='builder to use; default is html')
group.add_option('-a', action='store_true', dest='force_all',
help='write all files; default is to only write new and '
'changed files')
group.add_option('-E', action='store_true', dest='freshenv',
help='don\'t use a saved environment, always read '
'all files')
group.add_option('-d', metavar='PATH', default=None, dest='doctreedir',
help='path for the cached environment and doctree files '
'(default: outdir/.doctrees)')
group.add_option('-j', metavar='N', default=1, type='int', dest='jobs',
help='build in parallel with N processes where possible')
# this option never gets through to this point (it is intercepted earlier)
# group.add_option('-M', metavar='BUILDER', dest='make_mode',
# help='"make" mode -- as used by Makefile, like '
# '"sphinx-build -M html"')
group = parser.add_option_group('Build configuration options')
group.add_option('-c', metavar='PATH', dest='confdir',
help='path where configuration file (conf.py) is located '
'(default: same as sourcedir)')
group.add_option('-C', action='store_true', dest='noconfig',
help='use no config file at all, only -D options')
group.add_option('-D', metavar='setting=value', action='append',
dest='define', default=[],
help='override a setting in configuration file')
group.add_option('-A', metavar='name=value', action='append',
dest='htmldefine', default=[],
help='pass a value into HTML templates')
group.add_option('-t', metavar='TAG', action='append',
dest='tags', default=[],
help='define tag: include "only" blocks with TAG')
group.add_option('-n', action='store_true', dest='nitpicky',
help='nit-picky mode, warn about all missing references')
group = parser.add_option_group('Console output options')
group.add_option('-v', action='count', dest='verbosity', default=0,
help='increase verbosity (can be repeated)')
group.add_option('-q', action='store_true', dest='quiet',
help='no output on stdout, just warnings on stderr')
group.add_option('-Q', action='store_true', dest='really_quiet',
help='no output at all, not even warnings')
group.add_option('-N', action='store_true', dest='nocolor',
help='do not emit colored output')
group.add_option('-w', metavar='FILE', dest='warnfile',
help='write warnings (and errors) to given file')
group.add_option('-W', action='store_true', dest='warningiserror',
help='turn warnings into errors')
group.add_option('-T', action='store_true', dest='traceback',
help='show full traceback on exception')
group.add_option('-P', action='store_true', dest='pdb',
help='run Pdb on exception')
# parse options
try:
opts, args = parser.parse_args(argv[1:])
except SystemExit as err:
return err.code
# handle basic options
if opts.version:
print('Sphinx (sphinx-build) %s' % __version__)
return 0
# get paths (first and second positional argument)
try:
srcdir = abspath(args[0])
confdir = abspath(opts.confdir or srcdir)
if opts.noconfig:
confdir = None
if not path.isdir(srcdir):
print('Error: Cannot find source directory `%s\'.' % srcdir,
file=sys.stderr)
return 1
if not opts.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[1])
except IndexError:
usage(argv, 'Error: Insufficient arguments.')
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[2:]
#.........这里部分代码省略.........
开发者ID:lehmannro,项目名称:sphinx-mirror,代码行数:101,代码来源:cmdline.py
示例17: main
#.........这里部分代码省略.........
print('Error: source directory and destination directory are same.',
file=sys.stderr)
return 1
except IndexError:
parser.print_help()
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[2:]
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 opts.force_all and filenames:
print('Error: Cannot combine -a option and filenames.', file=sys.stderr)
return 1
if opts.color == 'no' or (opts.color == 'auto' and not color_terminal()):
nocolor()
doctreedir = abspath(opts.doctreedir or path.join(outdir, '.doctrees'))
status = sys.stdout
warning = sys.stderr
error = sys.stderr
if opts.quiet:
status = None
if opts.really_quiet:
status = warning = None
if warning and opts.warnfile:
try:
warnfp = open(opts.warnfile, 'w')
except Exception as exc:
print('Error: Cannot open warning file %r: %s' %
(opts.warnfile, exc), file=sys.stderr)
sys.exit(1)
warning = Tee(warning, warnfp) # type: ignore
error = warning
confoverrides = {}
for val in opts.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:
开发者ID:nwf,项目名称:sphinx,代码行数:67,代码来源:cmdline.py
示例18: build_main
def build_main(argv=sys.argv[1:]):
# type: (List[str]) -> int
"""Sphinx build "main" command-line entry."""
parser = get_parser()
args = parser.parse_args(argv)
if args.noconfig:
args.confdir = None
elif not args.confdir:
args.confdir = args.sourcedir
if not args.doctreedir:
args.doctreedir = os.path.join(args.outputdir, '.doctrees')
# handle remaining filename arguments
filenames = args.filenames
missing_files = []
for filename in filenames:
if not os.path.isfile(filename):
missing_files.append(filename)
if missing_files:
parser.error(__('cannot find files %r') % missing_files)
if args.force_all and filenames:
parser.error(__('cannot combine -a option and filenames'))
if args.color == 'no' or (args.color == 'auto' and not color_terminal()):
nocolor()
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:
parser.error(__('cannot open warning file %r: %s') % (
args.warnfile, exc))
warning = Tee(warning, warnfp) # type: ignore
error = warning
confoverrides = {}
for val in args.define:
try:
key, val = val.split('=', 1)
except ValueError:
parser.error(__('-D option argument must be in the form name=value'))
confoverrides[key] = val
for val in args.htmldefine:
try:
key, val = val.split('=')
except ValueError:
parser.error(__('-A option argument must be in the form name=value'))
try:
val = int(val)
except ValueError:
pass
confoverrides['html_context.%s' % key] = val
if args.nitpicky:
confoverrides['nitpicky'] = True
app = None
try:
confdir = args.confdir or args.sourcedir
with patch_docutils(confdir), docutils_namespace():
app = Sphinx(args.sourcedir, args.confdir, args.outputdir,
args.doctreedir, args.builder, confoverrides, status,
warning, args.freshenv, args.warningiserror,
args.tags, args.verbosity, args.jobs, args.keep_going)
app.build(args.force_all, filenames)
return app.statuscode
except (Exception, KeyboardInterrupt) as exc:
handle_exception(app, args, exc, error)
return 2
开发者ID:olivier-heurtier,项目名称:sphinx,代码行数:84,代码来源:build.py
示例19: main
def main(argv=sys.argv):
if not color_terminal():
nocolor()
parser = optparse.OptionParser(
USAGE, epilog=EPILOG, version="Sphinx v%s" % __display_version__, formatter=MyFormatter()
)
parser.add_option("-q", "--quiet", action="store_true", dest="quiet", default=False, help="quiet mode")
group = parser.add_option_group("Structure options")
group.add_option("--sep", action="store_true", dest="sep", help="if specified, separate source and build dirs")
group.add_option("--dot", metavar="DOT", dest="dot", help="replacement for dot in _templates etc.")
group = parser.add_option_group("Project basic options")
group.add_option("-p", "--project", metavar="PROJECT", dest="project", help="project name")
group.add_option("-a", "--author", metavar="AUTHOR", dest="author", help="author names")
group.add_option("-v", metavar="VERSION", dest="version", help="version of project")
group.add_option("-r", "--release", metavar="RELEASE", dest="release", help="release of project")
group.add_option("-l", "--language", metavar="LANGUAGE", dest="language", help="document language")
group.add_option("--suffix", metavar="SUFFIX", dest="suffix", help="source file suffix")
group.add_option("--master", metavar="MASTER", dest="master", help="master document name")
group.add_option("--epub", action="store_true", dest="epub", default=False, help="use epub")
group = parser.add_option_group("Extension options")
for ext in EXTENSIONS:
group.add_option(
"--ext-" + ext, action="store_true", dest="ext_" + ext, default=False, help="enable %s extension" % ext
)
group = parser.add_option_group("Makefile and Batchfile creation")
group.add_option("--makefile", action="store_true", dest="makefile", default=False, help="create makefile")
group.add_option(
"--no-makefile", action="store_true", dest="no_makefile", default=False, help="not create makefile"
)
group.add_option("--batchfile", action="store_true", dest="batchfile", default=False, help="create batchfile")
group.add_option(
"--no-batchfile", action="store_true", dest="no_batchfile", default=False, help="not create batchfile"
)
group.add_option(
"-M",
"--no-use-make-mode",
action="store_false",
dest="make_mode",
help="not use make-mode for Makefile/make.bat",
)
group.add_option(
"-m",
"--use-make-mode",
action="store_true",
dest="make_mode",
default=True,
help="use make-mode for Makefile/make.bat",
)
# parse options
try:
opts, args = parser.parse_args(argv[1:])
except SystemExit as err:
return err.code
if len(args) > 0:
opts.ensure_value("path", args[0])
d = vars(opts)
# 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 = DEFAULT_VALUE.copy()
d2.update(dict(("ext_" + ext, False) for ext in EXTENSIONS))
d2.update(d)
d = d2
if "no_makefile" in d:
d["makefile"] = False
if "no_batchfile" in d:
d["batchfile"] = False
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 ro
|
请发表评论