コード例 #1
0
ファイル: application.py プロジェクト: yangshiwei/ipython
    def print_help(self, classes=False):
        """Print the help for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        """
        self.print_description()
        self.print_subcommands()
        self.print_options()

        if classes:
            if self.classes:
                print("Class parameters")
                print("----------------")
                print()
                for p in wrap_paragraphs(self.keyvalue_description):
                    print(p)
                    print()

            for cls in self.classes:
                cls.class_print_help()
                print()
        else:
            print("To see all available configurables, use `--help-all`")
            print()

        self.print_examples()
コード例 #2
0
    def class_get_trait_help(cls, trait, inst=None):
        """Get the help string for a single trait.
        
        If `inst` is given, it's current trait values will be used in place of
        the class default.
        """
        assert inst is None or isinstance(inst, cls)
        lines = []
        header = "--%s.%s=<%s>" % (cls.__name__, trait.name, trait.__class__.__name__)
        lines.append(header)
        if inst is not None:
            lines.append(indent('Current: %r' % getattr(inst, trait.name), 4))
        else:
            try:
                dvr = repr(trait.get_default_value())
            except Exception:
                dvr = None # ignore defaults we can't construct
            if dvr is not None:
                if len(dvr) > 64:
                    dvr = dvr[:61]+'...'
                lines.append(indent('Default: %s' % dvr, 4))
        if 'Enum' in trait.__class__.__name__:
            # include Enum choices
            lines.append(indent('Choices: %r' % (trait.values,)))

        help = trait.get_metadata('help')
        if help is not None:
            help = '\n'.join(wrap_paragraphs(help, 76))
            lines.append(indent(help, 4))
        return '\n'.join(lines)
コード例 #3
0
ファイル: cmdline.py プロジェクト: jchodera/mixtape
    def _build_parser(self):
        # Using a custom "MyHelpFormatter" to monkey-patch argparse into making
        # all of the subcommands get rendered in the help text on one line. To
        # do this, you need to increase the "action_max_length" argument which
        # puts more whitespace between the end of the action name and the start
        # of the helptext.
        parser = argparse.ArgumentParser(
            description=self.description, formatter_class=lambda prog: MyHelpFormatter(prog,
            indent_increment=1, width=88, action_max_length=17))

        subparsers = parser.add_subparsers(dest=self.subcommand_dest, title="commands", metavar="")
        for klass in self._subcommands():
            # http://stackoverflow.com/a/17124446/1079728
            klass_description = klass.description
            if callable(klass_description):
                klass_description = klass_description()

            first_sentence = ' '.join(
                ' '.join(re.split(r'(?<=[.:;])\s', klass_description)[:1]).split())
            description = '\n\n'.join(wrap_paragraphs(klass_description))
            subparser = subparsers.add_parser(
                klass._get_name(), help=first_sentence, description=description, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
            for v in (getattr(klass, e) for e in dir(klass)):
                if isinstance(v, (argument, argument_group, mutually_exclusive_group)):
                    if v.parent is None:
                        v.register(subparser)
            if issubclass(klass, NumpydocClassCommand):
                klass._register_arguments(subparser)

        return parser
コード例 #4
0
def export_latex(fname):
    with open(fname) as f:
        nb = current.read(f, 'json')
    lines = ''
    for cell in nb.worksheets[0].cells:
        if cell.cell_type == u'code':
            lines += '\\begin{verbatim}\n'
            lines += '%s\n' % cell.input
            lines += '\\end{verbatim}\n'
            for output in cell.outputs:
                if output.output_type == u'pyout':
                    if hasattr(output, 'latex'):
                        lines += '%s\n' % output.latex
                    else:
                        lines += '\n'
                        lines += '\\begin{verbatim}\n'
                        lines += '%s\n' % output.text
                        lines += '\\end{verbatim}\n'
            lines += '\n'
        if cell.cell_type == u'markdown':
            paragraphs = wrap_paragraphs(cell.source)
            for p in paragraphs:
                lines += p
                lines += '\n\n'
    newfname = os.path.splitext(fname)[0] + '.tex'
    with open(newfname, 'w') as f:
        f.write(lines.encode('utf8'))
コード例 #5
0
    def print_alias_help(self):
        """Print the alias part of the help."""
        if not self.aliases:
            return

        lines = ['Aliases']
        lines.append('-' * len(lines[0]))
        lines.append('')
        for p in wrap_paragraphs(self.alias_description):
            lines.append(p)
            lines.append('')

        classdict = {}
        for cls in self.classes:
            # include all parents (up to, but excluding Configurable) in available names
            for c in cls.mro()[:-3]:
                classdict[c.__name__] = c

        for alias, longname in self.aliases.iteritems():
            classname, traitname = longname.split('.', 1)
            cls = classdict[classname]

            trait = cls.class_traits(config=True)[traitname]
            help = cls.class_get_trait_help(trait)
            help = help.replace(longname, "%s (%s)" % (alias, longname), 1)
            lines.append(help)
        lines.append('')
        print '\n'.join(lines)
コード例 #6
0
ファイル: application.py プロジェクト: pyarnold/ipython
    def print_help(self, classes=False):
        """Print the help for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        """
        self.print_description()
        self.print_subcommands()
        self.print_options()

        if classes:
            if self.classes:
                print("Class parameters")
                print("----------------")
                print()
                for p in wrap_paragraphs(self.keyvalue_description):
                    print(p)
                    print()

            for cls in self.classes:
                cls.class_print_help()
                print()
        else:
            print("To see all available configurables, use `--help-all`")
            print()

        self.print_examples()
コード例 #7
0
ファイル: exportlatex.py プロジェクト: jrioux/sympy-qcpaper
def export_latex(fname):
    with open(fname) as f:
        nb = current.read(f, 'json')
    lines = ''
    for cell in nb.worksheets[0].cells:
        if cell.cell_type == u'code':
            lines += '\\begin{verbatim}\n'
            lines += '%s\n' % cell.input
            lines += '\\end{verbatim}\n'
            for output in cell.outputs:
                if output.output_type == u'pyout':
                    if hasattr(output, 'latex'):
                        lines += '%s\n' % output.latex
                    else:
                        lines += '\n'
                        lines += '\\begin{verbatim}\n'
                        lines += '%s\n' % output.text
                        lines += '\\end{verbatim}\n'
            lines += '\n'
        if cell.cell_type == u'markdown':
            paragraphs = wrap_paragraphs(cell.source)
            for p in paragraphs:
                lines += p
                lines += '\n\n'
    newfname = os.path.splitext(fname)[0] + '.tex'
    with open(newfname,'w') as f:
        f.write(lines.encode('utf8'))
コード例 #8
0
    def class_get_trait_help(cls, trait, inst=None):
        """Get the help string for a single trait.
        
        If `inst` is given, it's current trait values will be used in place of
        the class default.
        """
        assert inst is None or isinstance(inst, cls)
        lines = []
        header = "--%s.%s=<%s>" % (cls.__name__, trait.name,
                                   trait.__class__.__name__)
        lines.append(header)
        if inst is not None:
            lines.append(indent('Current: %r' % getattr(inst, trait.name), 4))
        else:
            try:
                dvr = repr(trait.get_default_value())
            except Exception:
                dvr = None  # ignore defaults we can't construct
            if dvr is not None:
                if len(dvr) > 64:
                    dvr = dvr[:61] + '...'
                lines.append(indent('Default: %s' % dvr, 4))
        if 'Enum' in trait.__class__.__name__:
            # include Enum choices
            lines.append(indent('Choices: %r' % (trait.values, )))

        help = trait.get_metadata('help')
        if help is not None:
            help = '\n'.join(wrap_paragraphs(help, 76))
            lines.append(indent(help, 4))
        return '\n'.join(lines)
コード例 #9
0
ファイル: application.py プロジェクト: dhomeier/ipython-py3k
 def print_alias_help(self):
     """Print the alias part of the help."""
     if not self.aliases:
         return
     
     lines = ['Aliases']
     lines.append('-'*len(lines[0]))
     lines.append('')
     for p in wrap_paragraphs(self.alias_description):
         lines.append(p)
         lines.append('')
     
     classdict = {}
     for cls in self.classes:
         # include all parents (up to, but excluding Configurable) in available names
         for c in cls.mro()[:-3]:
             classdict[c.__name__] = c
     
     for alias, longname in self.aliases.items():
         classname, traitname = longname.split('.',1)
         cls = classdict[classname]
         
         trait = cls.class_traits(config=True)[traitname]
         help = cls.class_get_trait_help(trait)
         help = help.replace(longname, "%s (%s)"%(alias, longname), 1)
         lines.append(help)
     lines.append('')
     print('\n'.join(lines))
コード例 #10
0
ファイル: app.py プロジェクト: rmcgibbo/msmbuilder3
    def print_description(self):
        "Print the application description"
        lines = [""]
        lines.append(wrap_paragraphs(self.short_description)[0])
        lines.append("=" * min(79, len(lines[-1])))
        lines.append("")

        if self.long_description:
            for l in wrap_paragraphs(self.long_description):
                lines.append(l)
                lines.append("")

        if self.reference:
            lines.append("Reference\n---------")
            for l in wrap_paragraphs(self.reference):
                lines.append(l)
                lines.append("")

        print(os.linesep.join(lines))
コード例 #11
0
ファイル: app.py プロジェクト: yongwangCPH/msmaccelerator2
 def print_description(self):
     "Print the application description"
     lines = []
     lines.append(self.short_description)
     lines.append("=" * len(self.short_description))
     lines.append("")
     for l in wrap_paragraphs(self.long_description):
         lines.append(l)
         lines.append("")
     print(os.linesep.join(lines))
コード例 #12
0
ファイル: app.py プロジェクト: rmcgibbo/msmbuilder_config
    def print_description(self):
        "Print the application description"
        lines = []
        lines.append(self.short_description)
        lines.append('='*len(self.short_description))
        lines.append('')

        if self.long_description:
            for l in wrap_paragraphs(self.long_description):
                lines.append(l)
                lines.append('')

        if self.reference:
            lines.append('Reference\n---------')
            for l in wrap_paragraphs(self.reference):
                lines.append(l)
                lines.append('')

        print(os.linesep.join(lines))
コード例 #13
0
ファイル: app.py プロジェクト: mpharrigan/msmaccelerator2
 def print_description(self):
     "Print the application description"
     lines = []
     lines.append(self.short_description)
     lines.append('=' * len(self.short_description))
     lines.append('')
     for l in wrap_paragraphs(self.long_description):
         lines.append(l)
         lines.append('')
     print(os.linesep.join(lines))
コード例 #14
0
ファイル: application.py プロジェクト: filmor/ipython
 def print_options(self):
     if not self.flags and not self.aliases:
         return
     lines = ["Options"]
     lines.append("-" * len(lines[0]))
     lines.append("")
     for p in wrap_paragraphs(self.option_description):
         lines.append(p)
         lines.append("")
     print os.linesep.join(lines)
     self.print_flag_help()
     self.print_alias_help()
     print
コード例 #15
0
ファイル: application.py プロジェクト: yangshiwei/ipython
 def print_options(self):
     if not self.flags and not self.aliases:
         return
     lines = ['Options']
     lines.append('-' * len(lines[0]))
     lines.append('')
     for p in wrap_paragraphs(self.option_description):
         lines.append(p)
         lines.append('')
     print(os.linesep.join(lines))
     self.print_flag_help()
     self.print_alias_help()
     print()
コード例 #16
0
ファイル: application.py プロジェクト: pyarnold/ipython
 def print_options(self):
     if not self.flags and not self.aliases:
         return
     lines = ['Options']
     lines.append('-' * len(lines[0]))
     lines.append('')
     for p in wrap_paragraphs(self.option_description):
         lines.append(p)
         lines.append('')
     print(os.linesep.join(lines))
     self.print_flag_help()
     self.print_alias_help()
     print()
コード例 #17
0
ファイル: application.py プロジェクト: pyarnold/ipython
    def print_subcommands(self):
        """Print the subcommand part of the help."""
        if not self.subcommands:
            return

        lines = ["Subcommands"]
        lines.append('-' * len(lines[0]))
        lines.append('')
        for p in wrap_paragraphs(self.subcommand_description):
            lines.append(p)
            lines.append('')
        for subc, (cls, help) in iteritems(self.subcommands):
            lines.append(subc)
            if help:
                lines.append(indent(dedent(help.strip())))
        lines.append('')
        print(os.linesep.join(lines))
コード例 #18
0
ファイル: application.py プロジェクト: studer/ipython
    def print_subcommands(self):
        """Print the subcommand part of the help."""
        if not self.subcommands:
            return

        lines = ["Subcommands"]
        lines.append('-' * len(lines[0]))
        lines.append('')
        for p in wrap_paragraphs(self.subcommand_description):
            lines.append(p)
            lines.append('')
        for subc, (cls, help) in self.subcommands.iteritems():
            lines.append(subc)
            if help:
                lines.append(indent(dedent(help.strip())))
        lines.append('')
        print os.linesep.join(lines)
コード例 #19
0
    def print_flag_help(self):
        """Print the flag part of the help."""
        if not self.flags:
            return

        lines = ['Flags']
        lines.append('-' * len(lines[0]))
        lines.append('')
        for p in wrap_paragraphs(self.flag_description):
            lines.append(p)
            lines.append('')

        for m, (cfg, help) in self.flags.iteritems():
            lines.append('--' + m)
            lines.append(indent(dedent(help.strip())))
        lines.append('')
        print '\n'.join(lines)
コード例 #20
0
ファイル: application.py プロジェクト: dhomeier/ipython-py3k
 def print_flag_help(self):
     """Print the flag part of the help."""
     if not self.flags:
         return
     
     lines = ['Flags']
     lines.append('-'*len(lines[0]))
     lines.append('')
     for p in wrap_paragraphs(self.flag_description):
         lines.append(p)
         lines.append('')
     
     for m, (cfg,help) in self.flags.items():
         lines.append('--'+m)
         lines.append(indent(dedent(help.strip())))
     lines.append('')
     print('\n'.join(lines))
コード例 #21
0
def document_config_options(classes):
    lines = []
    for cls in classes:
        classname = cls.__name__
        for k, trait in sorted(cls.class_traits(config=True).items()):
            ttype = trait.__class__.__name__

            termline = classname + '.' + trait.name

            # Choices or type
            if 'Enum' in ttype:
                # include Enum choices
                termline += ' : ' + '|'.join(repr(x) for x in trait.values)
            else:
                termline += ' : ' + ttype
            lines.append(termline)

            # Default value
            try:
                dv = trait.get_default_value()
                dvr = repr(dv)
            except Exception:
                dvr = dv = None  # ignore defaults we can't construct
            if (dv is not None) and (dvr is not None):
                if len(dvr) > 64:
                    dvr = dvr[:61] + '...'
                # Double up backslashes, so they get to the rendered docs
                dvr = dvr.replace('\\n', '\\\\n')
                lines.append('    Default: ' + dvr)
                lines.append('')

            help = trait.get_metadata('help')
            if help is not None:
                help = '\n\n'.join(wrap_paragraphs(help, 76))
                lines.append(indent(help, 4))
            else:
                lines.append('    No description')

            lines.append('')
    return '\n'.join(lines)
コード例 #22
0
ファイル: autogen_config.py プロジェクト: chebee7i/ipython
def document_config_options(classes):
    lines = []
    for cls in classes:
        classname = cls.__name__
        for k, trait in sorted(cls.class_traits(config=True).items()):
            ttype = trait.__class__.__name__

            termline = classname + "." + trait.name

            # Choices or type
            if "Enum" in ttype:
                # include Enum choices
                termline += " : " + "|".join(repr(x) for x in trait.values)
            else:
                termline += " : " + ttype
            lines.append(termline)

            # Default value
            try:
                dv = trait.get_default_value()
                dvr = repr(dv)
            except Exception:
                dvr = dv = None  # ignore defaults we can't construct
            if (dv is not None) and (dvr is not None):
                if len(dvr) > 64:
                    dvr = dvr[:61] + "..."
                # Double up backslashes, so they get to the rendered docs
                dvr = dvr.replace("\\n", "\\\\n")
                lines.append("    Default: " + dvr)
                lines.append("")

            help = trait.get_metadata("help")
            if help is not None:
                help = "\n\n".join(wrap_paragraphs(help, 76))
                lines.append(indent(help, 4))
            else:
                lines.append("    No description")

            lines.append("")
    return "\n".join(lines)
コード例 #23
0
def document_config_options(classes):
    lines = []
    for cls in classes:
        classname = cls.__name__
        for k, trait in sorted(cls.class_traits(config=True).items()):
            ttype = trait.__class__.__name__

            termline = classname + '.' + trait.name

            # Choices or type
            if 'Enum' in ttype:
                # include Enum choices
                termline += ' : ' + '|'.join(repr(x) for x in trait.values)
            else:
                termline += ' : ' + ttype
            lines.append(termline)

            # Default value
            try:
                dv = trait.get_default_value()
                dvr = repr(dv)
            except Exception:
                dvr = dv = None # ignore defaults we can't construct
            if (dv is not None) and (dvr is not None):
                if len(dvr) > 64:
                    dvr = dvr[:61]+'...'
                # Double up backslashes, so they get to the rendered docs
                dvr = dvr.replace('\\n', '\\\\n')
                lines.append('    Default: ' + dvr)
                lines.append('')

            help = trait.get_metadata('help')
            if help is not None:
                help = '\n\n'.join(wrap_paragraphs(help, 76))
                lines.append(indent(help, 4))
            else:
                lines.append('    No description')

            lines.append('')
    return '\n'.join(lines)
コード例 #24
0
ファイル: configurable.py プロジェクト: pombredanne/ipython
 def class_get_trait_help(cls, trait):
     """Get the help string for a single trait."""
     lines = []
     header = "%s.%s : %s" % (cls.__name__, trait.name, trait.__class__.__name__)
     lines.append(header)
     try:
         dvr = repr(trait.get_default_value())
     except Exception:
         dvr = None # ignore defaults we can't construct
     if dvr is not None:
         if len(dvr) > 64:
             dvr = dvr[:61]+'...'
         lines.append(indent('Default: %s'%dvr, 4))
     if 'Enum' in trait.__class__.__name__:
         # include Enum choices
         lines.append(indent('Choices: %r'%(trait.values,)))
     
     help = trait.get_metadata('help')
     if help is not None:
         help = '\n'.join(wrap_paragraphs(help, 76))
         lines.append(indent(help, 4))
     return '\n'.join(lines)
コード例 #25
0
ファイル: cmdline.py プロジェクト: gkiss/mixtape
    def _build_parser(self):
        # Using a custom "MyHelpFormatter" to monkey-patch argparse into making
        # all of the subcommands get rendered in the help text on one line. To
        # do this, you need to increase the "action_max_length" argument which
        # puts more whitespace between the end of the action name and the start
        # of the helptext.
        parser = argparse.ArgumentParser(description=self.description,
            formatter_class=lambda prog: MyHelpFormatter(prog,
            indent_increment=1, width=88, action_max_length=17))

        subparsers = parser.add_subparsers(dest=self.subcommand_dest, title="commands", metavar="")
        for klass in self._subcommands():
            # http://stackoverflow.com/a/17124446/1079728
            first_sentence = ' '.join(' '.join(re.split(r'(?<=[.:;])\s', klass.description)[:1]).split())
            description = '\n\n'.join(wrap_paragraphs(klass.description))
            subparser = subparsers.add_parser(
                klass._get_name(), help=first_sentence, description=description, formatter_class=argparse.RawDescriptionHelpFormatter)
            for v in (getattr(klass, e) for e in dir(klass)):
                if isinstance(v, (argument, argument_group, mutually_exclusive_group)):
                    if v.parent is None:
                        v.register(subparser)

        return parser
コード例 #26
0
    def class_get_trait_help(cls, trait):
        """Get the help string for a single trait."""
        lines = []
        header = "--%s.%s=<%s>" % (cls.__name__, trait.name,
                                   trait.__class__.__name__)
        lines.append(header)
        try:
            dvr = repr(trait.get_default_value())
        except Exception:
            dvr = None  # ignore defaults we can't construct
        if dvr is not None:
            if len(dvr) > 64:
                dvr = dvr[:61] + '...'
            lines.append(indent('Default: %s' % dvr, 4))
        if 'Enum' in trait.__class__.__name__:
            # include Enum choices
            lines.append(indent('Choices: %r' % (trait.values, )))

        help = trait.get_metadata('help')
        if help is not None:
            help = '\n'.join(wrap_paragraphs(help, 76))
            lines.append(indent(help, 4))
        return '\n'.join(lines)
コード例 #27
0
        def c(s):
            """return a commented, wrapped block."""
            s = "\n\n".join(wrap_paragraphs(s, 78))

            return "# " + s.replace("\n", "\n# ")
コード例 #28
0
ファイル: application.py プロジェクト: pyarnold/ipython
 def print_description(self):
     """Print the application description."""
     for p in wrap_paragraphs(self.description):
         print(p)
         print()
コード例 #29
0
def export_latex(fname):
    with open(fname) as f:
        nb = current.read(f, 'json')
        
    base,ext=os.path.splitext(fname)
    figdirname=base
    if not os.path.exists(figdirname):
        os.mkdir(figdirname)
        
    lines = ''
    
    figcount=0
    figname,ext=os.path.splitext(fname)
    for cell in nb.worksheets[0].cells:
        if cell.cell_type == u'code':
            lines += '\\begin{lstlisting}\n'
            lines += '%s\n' % cell.input
            lines += '\\end{lstlisting}\n'
            for output in cell.outputs:
                if output.output_type == u'pyout':
                    if hasattr(output, 'latex'):
                        s=output.latex
                        s=s.replace(r"\\[",r"\[")
                        s=s.replace(r"\\]",r"\]")
                        lines += '%s\n' % s
                    else:
                        lines += '\n'
                        lines += '\\begin{verbatim}\n'
                        lines += '%s\n' % output.text
                        lines += '\\end{verbatim}\n'
                elif str(output.output_type) == 'display_data':
                    if 'png' in output:
                        pic=output['png'].decode('base64')
                        fig_fname='%s/%s_fig%d.png' % (figdirname,figname,figcount)
                        fopen = lambda fname: open(fname, 'wb')
                        print "Writing %s..." % fig_fname
                        with fopen(fig_fname) as f:
                            f.write(pic)

                        lines += '\n'
#                         lines += '(see Figure~\\ref{%s_%d})\n' % (figname,figcount)
#                         lines += '\\begin{figure*}\n'
                        lines += '\\begin{center}\\includegraphics[width=4.5in]{%s}\\end{center}\n' % (fig_fname)
#                         lines += '\\label{%s_%d}\n' % (figname,figcount)
#                         lines += '\\end{figure*}\n'
                        
                        figcount+=1
                    elif 'text' in output:
                        lines += '\n'
                        lines += '\\begin{verbatim}\n'
                        lines += '%s' % output.text
                        lines += '\\end{verbatim}\n'                    
                        
                    else:
                        print "Unknown output type",output.output_type
                        print output
                        print "input",cell.input
                    
                elif output.output_type == u'stream':
                    lines += '\n'
                    lines += '\\begin{verbatim}\n'
                    lines += '%s' % output.text
                    lines += '\\end{verbatim}\n'                    
                else:
                    print "Unknown output type",output.output_type
                    print type(output.output_type)
                    print output
                    print "input",cell.input
                
            lines += '\n'
        elif cell.cell_type == u'markdown':
            paragraphs = wrap_paragraphs(cell.source)
            for p in paragraphs:
                s=p
                s=s.replace(r"\\[",r"\[")
                s=s.replace(r"\\]",r"\]")
            
                if s.startswith('## '):
                    s=r"\subsection{%s}" % (s[3:].strip())
                    s+="\n"
                if s.startswith('### '):
                    s=r"\subsubsection{%s}" % (s[3:].strip())
                    s+="\n"
            
                lines += s
                lines += '\n\n'
        else:
            print "Unknown cell type",cell.cell_type
            
    newfname = os.path.splitext(fname)[0] + '.tex'
    with open(newfname,'w') as f:
        f.write(lines.encode('utf8'))
コード例 #30
0
        def c(s):
            """return a commented, wrapped block."""
            s = '\n\n'.join(wrap_paragraphs(s, 78))

            return '# ' + s.replace('\n', '\n# ')
コード例 #31
0
ファイル: application.py プロジェクト: yangshiwei/ipython
 def print_description(self):
     """Print the application description."""
     for p in wrap_paragraphs(self.description):
         print(p)
         print()
コード例 #32
0
def export_latex(fname):
    with open(fname) as f:
        nb = current.read(f, 'json')

    base, ext = os.path.splitext(fname)
    figdirname = base
    if not os.path.exists(figdirname):
        os.mkdir(figdirname)

    lines = ''

    figcount = 0
    figname, ext = os.path.splitext(fname)
    for cell in nb.worksheets[0].cells:
        if cell.cell_type == u'code':
            lines += '\\begin{lstlisting}\n'
            lines += '%s\n' % cell.input
            lines += '\\end{lstlisting}\n'
            for output in cell.outputs:
                if output.output_type == u'pyout':
                    if hasattr(output, 'latex'):
                        s = output.latex
                        s = s.replace(r"\\[", r"\[")
                        s = s.replace(r"\\]", r"\]")
                        lines += '%s\n' % s
                    else:
                        lines += '\n'
                        lines += '\\begin{verbatim}\n'
                        lines += '%s\n' % output.text
                        lines += '\\end{verbatim}\n'
                elif str(output.output_type) == 'display_data':
                    if 'png' in output:
                        pic = output['png'].decode('base64')
                        fig_fname = '%s/%s_fig%d.png' % (figdirname, figname,
                                                         figcount)
                        fopen = lambda fname: open(fname, 'wb')
                        print "Writing %s..." % fig_fname
                        with fopen(fig_fname) as f:
                            f.write(pic)

                        lines += '\n'
                        #                         lines += '(see Figure~\\ref{%s_%d})\n' % (figname,figcount)
                        #                         lines += '\\begin{figure*}\n'
                        lines += '\\begin{center}\\includegraphics[width=4.5in]{%s}\\end{center}\n' % (
                            fig_fname)
                        #                         lines += '\\label{%s_%d}\n' % (figname,figcount)
                        #                         lines += '\\end{figure*}\n'

                        figcount += 1
                    elif 'text' in output:
                        lines += '\n'
                        lines += '\\begin{verbatim}\n'
                        lines += '%s' % output.text
                        lines += '\\end{verbatim}\n'

                    else:
                        print "Unknown output type", output.output_type
                        print output
                        print "input", cell.input

                elif output.output_type == u'stream':
                    lines += '\n'
                    lines += '\\begin{verbatim}\n'
                    lines += '%s' % output.text
                    lines += '\\end{verbatim}\n'
                else:
                    print "Unknown output type", output.output_type
                    print type(output.output_type)
                    print output
                    print "input", cell.input

            lines += '\n'
        elif cell.cell_type == u'markdown':
            paragraphs = wrap_paragraphs(cell.source)
            for p in paragraphs:
                s = p
                s = s.replace(r"\\[", r"\[")
                s = s.replace(r"\\]", r"\]")

                if s.startswith('## '):
                    s = r"\subsection{%s}" % (s[3:].strip())
                    s += "\n"
                if s.startswith('### '):
                    s = r"\subsubsection{%s}" % (s[3:].strip())
                    s += "\n"

                lines += s
                lines += '\n\n'
        else:
            print "Unknown cell type", cell.cell_type

    newfname = os.path.splitext(fname)[0] + '.tex'
    with open(newfname, 'w') as f:
        f.write(lines.encode('utf8'))
コード例 #33
0
ファイル: configurable.py プロジェクト: grahame/ipython-py3k
 def c(s):
     """return a commented, wrapped block."""
     s = '\n\n'.join(wrap_paragraphs(s, 78))
     
     return '# ' + s.replace('\n', '\n# ')