• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python console.nocolor函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sphinx.util.console.nocolor函数的典型用法代码示例。如果您正苦于以下问题:Python nocolor函数的具体用法?Python nocolor怎么用?Python nocolor使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了nocolor函数的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: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


示例2: 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


示例3: run

    def run(self):
        if not sys.stdout.isatty() or sys.platform == 'win32':
            # 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:BackupGGCode,项目名称:sphinx,代码行数:25,代码来源:setup_command.py


示例4: 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


示例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: run

    def run(self):
        if is_sphinx_installed():
            from sphinx.application import Sphinx
            from sphinx.util.console import nocolor

            # Windows' poor cmd box doesn't understand ANSI sequences
            if not sys.stdout.isatty() or sys.platform == 'win32':
                nocolor()

            # Check to see if version information is provided in setup.py
            # If it is, it will override version information in conf.py.
            conf_overrides = {}
            version = self.distribution.get_version()
            if version != "0.0.0":
                conf_overrides['version'] = version
                conf_overrides['release'] = version

            for i in range(len(self.source_dirs)):
                for format in self.formats:
                    try:
                        builder_target = os.path.join(self.target_dir, format,
                            self.projects[i])
                        doctree_dir = os.path.join(builder_target, '.doctrees')

                        self.mkpath(doctree_dir)

                        # The sphinx interface requires 7 arguments: sourcedir,
                        # confdir, outdir, doctreedir, buildername,
                        # confoverrides, and status
                        app = Sphinx(self.source_dirs[i], self.source_dirs[i],
                            builder_target, doctree_dir, format, conf_overrides,
                            self.status_stream
                            )
                        app.builder.build_update()
                        if self.pdf_build and format == 'latex':
                            try:
                                os.chdir(builder_target)
                                subprocess.call(["make", "all-pdf"])
                                log.info("PDF doc created in %s."
                                    % builder_target)
                            except Exception, e:
                                log.error(e)

                    except IOError, e:
                        log.warn(e)

                    except Exception, e:
                        log.error('Unable to generate %s docs.' % format)
                        if format == 'html' and len(self.formats) == 1:
                            log.info("Installing %s html documentation from zip"
                                     " file.\n" % self.distribution.get_name())
                            unzip_html_docs(HTML_ZIP, TARGET_DIR)
开发者ID:hitej,项目名称:meta-core,代码行数:52,代码来源:setupdocs.py


示例9: 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


示例10: 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


示例11: 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


示例12: 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


示例13: 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


示例14: 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


示例15: 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


示例16: inner_main

def inner_main(args):
    d = {}

    if os.name == 'nt' or not sys.stdout.isatty():
        nocolor()

    print bold('Welcome to the Sphinx quickstart utility.')
    print '''
Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).'''

    print '''
Enter the root path for documentation.'''
    do_prompt(d, 'path', 'Root path for the documentation', '.', is_path)
    print '''
You have two options for placing the build directory for Sphinx output.
Either, you use a directory ".build" within the root path, or you separate
"source" and "build" directories within the root path.'''
    do_prompt(d, 'sep', 'Separate source and build directories (y/n)', 'n',
              boolean)
    print '''
Inside the root directory, two more directories will be created; ".templates"
for custom HTML templates and ".static" for custom stylesheets and other
static files. Since the leading dot may be inconvenient for Windows users,
you can enter another prefix (such as "_") to replace the dot.'''
    do_prompt(d, 'dot', 'Name prefix for templates and static dir', '.', ok)

    print '''
The project name will occur in several places in the built documentation.'''
    do_prompt(d, 'project', 'Project name')
    do_prompt(d, 'author', 'Author name(s)')
    print '''
Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.'''
    do_prompt(d, 'version', 'Project version')
    do_prompt(d, 'release', 'Project release', d['version'])
    print '''
The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.'''
    do_prompt(d, 'suffix', 'Source file suffix', '.rst', suffix)
    print '''
One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.'''
    do_prompt(d, 'master', 'Name of your master document (without suffix)',
              'index')
    print '''
Please indicate if you want to use one of the following Sphinx extensions:'''
    do_prompt(d, 'ext_autodoc', 'autodoc: automatically insert docstrings '
              'from modules (y/n)', 'n', boolean)
    do_prompt(d, 'ext_doctest', 'doctest: automatically test code snippets '
              'in doctest blocks (y/n)', 'n', boolean)
    print '''
If you are under Unix, a Makefile can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.'''
    do_prompt(d, 'makefile', 'Create Makefile? (y/n)',
              os.name == 'posix' and 'y' or 'n', boolean)

    d['project_fn'] = make_filename(d['project'])
    d['year'] = time.strftime('%Y')
    d['now'] = time.asctime()
    d['underline'] = len(d['project']) * '='
    d['extensions'] = ', '.join(
        repr('sphinx.ext.' + name) for name in ('autodoc', 'doctest')
        if d['ext_' + name].upper() in ('Y', 'YES'))

    if not path.isdir(d['path']):
        mkdir_p(d['path'])

    separate = d['sep'].upper() in ('Y', 'YES')
    srcdir = separate and path.join(d['path'], 'source') or d['path']

    mkdir_p(srcdir)
    if separate:
        builddir = path.join(d['path'], 'build')
    else:
        builddir = path.join(srcdir, d['dot'] + 'build')
    mkdir_p(builddir)
    mkdir_p(path.join(srcdir, d['dot'] + 'templates'))
    mkdir_p(path.join(srcdir, d['dot'] + 'static'))

    f = open(path.join(srcdir, 'conf.py'), 'w')
    f.write(QUICKSTART_CONF % d)
    f.close()

    masterfile = path.join(srcdir, d['master'] + d['suffix'])
    f = open(masterfile, 'w')
    f.write(MASTER_FILE % d)
    f.close()

    create_makefile = d['makefile'].upper() in ('Y', 'YES')
    if create_makefile:
        d['rsrcdir'] = separate and 'source' or '.'
        d['rbuilddir'] = separate and 'build' or d['dot'] + 'build'
        f = open(path.join(d['path'], 'Makefile'), 'w')
#.........这里部分代码省略.........
开发者ID:lshmenor,项目名称:IMTAphy,代码行数:101,代码来源:quickstart.py


示例17: run


#.........这里部分代码省略.........
                    configure_file(environ,
                                   os.path.join(doc_dir, dext.doxygen_cfg),
                                   os.path.join(working_dir, dext.doxygen_cfg),
                                   style=dext.style)
                    for s in dext.doxygen_srcs:
                        configure_file(environ,
                                       os.path.join(doc_dir, s),
                                       os.path.join(working_dir, s),
                                       style=dext.style)
                    try:
                        doxygen_exe = find_program('doxygen')
                    except Exception:  # pylint: disable=W0703
                        sys.stderr.write('ERROR: Doxygen not installed ' +
                                         '(required for documentation).\n')
                        return

                    reprocess = True
                    ref = os.path.join(working_dir, 'html', 'index.html')
                    if os.path.exists(ref) and not self.force:
                        reprocess = False
                        for d in environ['C_SOURCE_DIRS'].split(' '):
                            for orig in glob.glob(os.path.join(d, '*.h*')):
                                if os.path.getmtime(ref) < \
                                   os.path.getmtime(orig):
                                    reprocess = True
                                    break
                    if reprocess:
                        if self.distribution.verbose:
                            out = sys.stdout
                            err = sys.stderr
                        else:
                            out = err = open('doxygen.log', 'w')
                        os.chdir(working_dir)
                        cmd_line = [doxygen_exe, dext.doxygen_cfg]
                        status = subprocess.call(cmd_line,
                                                 stdout=out, stderr=err)
                        if status != 0:
                            raise Exception("Command '" + str(cmd_line) +
                                            "' returned non-zero exit status "
                                            + str(status))

                        if not self.distribution.verbose:
                            out.close()
                        copy_tree('html', os.path.join(target, 'html'), True,
                                  excludes=['.svn', 'CVS', '.git', '.hg*'])
                        copy_tree('xml', os.path.join(cfg_dir, 'xml'), True)
                        os.chdir(here)
                        create_breathe_stylesheet(target)

                for f in dext.extra_docs:
                    shutil.copy(os.path.join(doc_dir, f), target)

                ## Sphinx
                if dext.without_sphinx:
                    return
                if dext.sphinx_config is None:
                    level_up = os.path.dirname(os.path.dirname(__file__))
                    dext.sphinx_config = os.path.join(level_up,
                                                      'sphinx_conf.py.in')
                elif os.path.dirname(dext.sphinx_config) == '':
                    dext.sphinx_config =  os.path.join(doc_dir,
                                                       dext.sphinx_config)
                configure_file(environ, dext.sphinx_config,
                               os.path.join(cfg_dir, 'conf.py'))
                import warnings
                try:
                    import sphinx  # pylint: disable=W0612
                except ImportError:
                    configure_package('breathe')  ## requires sphinx
                    sys.path.insert(0, os.path.join(options.target_build_dir,
                                                    options.local_lib_dir))

                from sphinx.application import Sphinx
                if 'windows' in platform.system().lower() or \
                   not build_verbose:
                    from sphinx.util.console import nocolor
                warnings.filterwarnings("ignore",
                                        category=PendingDeprecationWarning)
                warnings.filterwarnings("ignore", category=UserWarning)

                status = sys.stdout
                if not build_verbose:
                    status = open('sphinx.log', 'w')
                if 'windows' in platform.system().lower() or not build_verbose:
                    nocolor()
                try:
                    ## args: srcdir, confdir, outdir, doctreedir, buildername
                    sphinx_app = Sphinx(os.path.join(working_dir, dext.name),
                                        cfg_dir, target,
                                        os.path.join(target, '.doctrees'),
                                        'html', status=status)
                    sphinx_app.build(force_all=True, filenames=None)
                except Exception:  # pylint: disable=W0703
                    if build_verbose:
                        print('ERROR: ' + str(sys.exc_info()[1]))
                    else:
                        pass
                if not build_verbose:
                    status.close()
                warnings.resetwarnings()
开发者ID:sean-m-brennan,项目名称:pysysdevel,代码行数:101,代码来源:build_sphinx.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: setup_module

def setup_module():
    nocolor()
开发者ID:qsnake,项目名称:sphinx,代码行数:2,代码来源:test_quickstart.py


示例20: main

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python console.red函数代码示例发布时间:2022-05-27
下一篇:
Python console.darkgreen函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap