def main(): log_format = "%(asctime)s %(message)s" log_datefmt = "%m/%d/%Y %I:%M:%S %p" parser = argparse.ArgumentParser() parser.add_argument("input_file", help=".ipynb file to run") parser.add_argument("output_file", nargs="?", help=".ipynb file to save cell output to") parser.add_argument("--quiet", "-q", action="store_true", help="don't print anything unless things go wrong") parser.add_argument( "--overwrite", "-o", action="store_true", help="write notebook output back to original notebook" ) parser.add_argument("--html", nargs="?", default=False, help="output an HTML snapshot of the notebook") parser.add_argument("--pylab", action="store_true", help="start notebook with pylab enabled") parser.add_argument( "--skip-exceptions", "-s", action="store_true", help="if an exception occurs in a cell, continue running the subsequent cells", ) args = parser.parse_args() if args.overwrite: if args.output_file is not None: print("Error: output_filename must not be provided if " "--overwrite (-o) given", file=stderr) exit(1) else: args.output_file = args.input_file if not args.quiet: logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=log_datefmt) nb_runner = NotebookRunner(args.input_file, args.pylab) exit_status = 0 try: nb_runner.run_notebook(skip_exceptions=args.skip_exceptions) except NotebookError: exit_status = 1 if args.output_file: nb_runner.save_notebook(args.output_file) if args.html is not False: if args.html is None: # if --html is given but no filename is provided, # come up with a sane output name based on the # input filename if args.input_file.endswith(".ipynb"): args.html = args.input_file[:-6] + ".html" else: args.html = args.input_file + ".ipynb" logging.info("Saving HTML snapshot to %s" % args.html) exporter = HTMLExporter() output, resources = exporter.from_notebook_node(nb_runner.nb) codecs.open(args.html, "w", encoding="utf-8").write(output) if exit_status != 0: logging.warning("Exiting with nonzero exit status") exit(exit_status)
def export_to_html(nb_runner, args): """Export notebook to html format.""" if args.html is None: # if --html is given but no filename is provided, # come up with a sane output name based on the # input filename if args.input_file.endswith('.ipynb'): args.html = args.input_file[:-6] + '.html' else: args.html = args.input_file + '.html' if args.template is False: exporter = HTMLExporter() else: exporter = HTMLExporter( config=Config({'HTMLExporter':{'template_file':args.template, 'template_path': ['.', '/']}})) logging.info('Saving HTML snapshot to %s' % args.html) # output, resources = exporter.from_notebook_node(nb_runner.nb) # codecs.open(args.html, 'w', encoding='utf-8').write(output) with codecs.open(args.html, "w", encoding="utf-8") as fh: for worksheet in nb_runner.nb.worksheets: output, resources = exporter.from_notebook_node(worksheet) fh.write(output)
def main(): log_format = '%(asctime)s %(levelname)s: %(message)s' log_datefmt = '%m/%d/%Y %I:%M:%S %p' parser = argparse.ArgumentParser() parser.add_argument('--version', '-v', action='version', version=runipy.__version__, help='print version information') parser.add_argument('input_file', nargs='?', help='.ipynb file to run (or stdin)') parser.add_argument('output_file', nargs='?', help='.ipynb file to save cell output to') parser.add_argument('--quiet', '-q', action='store_true', help='don\'t print anything unless things go wrong') parser.add_argument('--overwrite', '-o', action='store_true', help='write notebook output back to original notebook') parser.add_argument('--html', nargs='?', default=False, help='output an HTML snapshot of the notebook') parser.add_argument('--template', nargs='?', default=False, help='template to use for HTML output') parser.add_argument('--pylab', action='store_true', help='start notebook with pylab enabled') parser.add_argument('--matplotlib', action='store_true', help='start notebook with matplotlib inlined') parser.add_argument('--skip-exceptions', '-s', action='store_true', help='if an exception occurs in a cell,' + ' continue running the subsequent cells') parser.add_argument( '--stdout', action='store_true', help='print notebook to stdout (or use - as output_file') parser.add_argument( '--stdin', action='store_true', help='read notebook from stdin (or use - as input_file)') parser.add_argument( '--no-chdir', action='store_true', help="do not change directory to notebook's at kernel startup") parser.add_argument('--profile-dir', help="set the profile location directly") args = parser.parse_args() if args.overwrite: if args.output_file is not None: print( 'Error: output_filename must not be provided if ' '--overwrite (-o) given', file=stderr) exit(1) else: args.output_file = args.input_file if not args.quiet: logging.basicConfig(level=logging.INFO, format=log_format, datefmt=log_datefmt) working_dir = None payload_source = "" payload = "" if args.input_file == '-' or args.stdin: # force stdin payload_source = stdin.name payload = stdin.read() elif not args.input_file and stdin.isatty(): # no force, empty stdin parser.print_help() exit() elif not args.input_file: # no file -> default stdin payload_source = stdin.name payload = stdin.read() else: # must have specified normal input_file with open(args.input_file) as input_file: payload_source = input_file.name payload = input_file.read() working_dir = os.path.dirname(args.input_file) if args.no_chdir: working_dir = None if args.profile_dir: profile_dir = os.path.expanduser(args.profile_dir) else: profile_dir = None logging.info('Reading notebook %s', payload_source) try: # Ipython 3 nb = reads(payload, 3) except (TypeError, NBFormatError): # Ipython 2 nb = reads(payload, 'json') nb_runner = NotebookRunner(nb, args.pylab, args.matplotlib, profile_dir, working_dir) exit_status = 0 try: nb_runner.run_notebook(skip_exceptions=args.skip_exceptions) except NotebookError: exit_status = 1 if args.output_file and args.output_file != '-': logging.info('Saving to %s', args.output_file) with open(args.output_file, 'w') as output_filehandle: try: # Ipython 3 write(nb_runner.nb, output_filehandle, 3) except (TypeError, NBFormatError): # Ipython 2 write(nb_runner.nb, output_filehandle, 'json') if args.stdout or args.output_file == '-': try: # Ipython 3 write(nb_runner.nb, stdout, 3) except (TypeError, NBFormatError): # Ipython 2 write(nb_runner.nb, stdout, 'json') print() if args.html is not False: if args.html is None: # if --html is given but no filename is provided, # come up with a sane output name based on the # input filename if args.input_file.endswith('.ipynb'): args.html = args.input_file[:-6] + '.html' else: args.html = args.input_file + '.html' if args.template is False: exporter = HTMLExporter() else: exporter = HTMLExporter(config=Config({ 'HTMLExporter': { 'template_file': args.template, 'template_path': ['.', '/'] } })) logging.info('Saving HTML snapshot to %s' % args.html) output, resources = exporter.from_notebook_node( convert(nb_runner.nb, current_nbformat)) codecs.open(args.html, 'w', encoding='utf-8').write(output) nb_runner.shutdown_kernel() if exit_status != 0: logging.warning('Exiting with nonzero exit status') exit(exit_status)
def main(): log_format = '%(asctime)s %(message)s' log_datefmt = '%m/%d/%Y %I:%M:%S %p' parser = argparse.ArgumentParser() parser.add_argument('input_file', help='.ipynb file to run') parser.add_argument('output_file', nargs='?', help='.ipynb file to save cell output to') parser.add_argument('--quiet', '-q', action='store_true', help='don\'t print anything unless things go wrong') parser.add_argument('--overwrite', '-o', action='store_true', help='write notebook output back to original notebook') parser.add_argument('--html', nargs='?', default=False, help='output an HTML snapshot of the notebook') parser.add_argument('--template', nargs='?', default=False, help='template to use for HTML output') parser.add_argument('--pylab', action='store_true', help='start notebook with pylab enabled') parser.add_argument('--matplotlib', action='store_true', help='start notebook with matplotlib inlined') parser.add_argument('--skip-exceptions', '-s', action='store_true', help='if an exception occurs in a cell, continue running the subsequent cells') args = parser.parse_args() if args.overwrite: if args.output_file is not None: print('Error: output_filename must not be provided if ' '--overwrite (-o) given', file=stderr) exit(1) else: args.output_file = args.input_file if not args.quiet: logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=log_datefmt) nb_runner = NotebookRunner(args.input_file, args.pylab, args.matplotlib) exit_status = 0 try: nb_runner.run_notebook(skip_exceptions=args.skip_exceptions, autosave = args.output_file) except NotebookError: exit_status = 1 if args.html is not False: if args.html is None: # if --html is given but no filename is provided, # come up with a sane output name based on the # input filename if args.input_file.endswith('.ipynb'): args.html = args.input_file[:-6] + '.html' else: args.html = args.input_file + '.ipynb' if args.template is False: exporter = HTMLExporter() else: exporter = HTMLExporter(config=Config({'HTMLExporter':{'default_template':args.template}})) logging.info('Saving HTML snapshot to %s' % args.html) output, resources = exporter.from_notebook_node(nb_runner.nb) codecs.open(args.html, 'w', encoding='utf-8').write(output) if exit_status != 0: logging.warning('Exiting with nonzero exit status') exit(exit_status)
def main(): log_format = '%(asctime)s %(levelname)s: %(message)s' log_datefmt = '%m/%d/%Y %I:%M:%S %p' parser = argparse.ArgumentParser() parser.add_argument('--version', '-v', action='version', version=runipy.__version__, help='print version information') parser.add_argument('input_file', nargs='?', help='.ipynb file to run (or stdin)') parser.add_argument('output_file', nargs='?', help='.ipynb file to save cell output to') parser.add_argument('--quiet', '-q', action='store_true', help='don\'t print anything unless things go wrong') parser.add_argument('--overwrite', '-o', action='store_true', help='write notebook output back to original notebook') parser.add_argument('--html', nargs='?', default=False, help='output an HTML snapshot of the notebook') parser.add_argument('--template', nargs='?', default=False, help='template to use for HTML output') parser.add_argument('--pylab', action='store_true', help='start notebook with pylab enabled') parser.add_argument('--matplotlib', action='store_true', help='start notebook with matplotlib inlined') parser.add_argument('--skip-exceptions', '-s', action='store_true', help='if an exception occurs in a cell, continue running the subsequent cells') parser.add_argument('--stdout', action='store_true', help='print notebook to stdout (or use - as output_file') parser.add_argument('--stdin', action='store_true', help='read notebook from stdin (or use - as input_file)') parser.add_argument('--no-chdir', action='store_true', help="do not change directory to notebook's at kernel startup") parser.add_argument('--profile-dir', help="set the profile location directly") args = parser.parse_args() if args.overwrite: if args.output_file is not None: print('Error: output_filename must not be provided if ' '--overwrite (-o) given', file=stderr) exit(1) else: args.output_file = args.input_file if not args.quiet: logging.basicConfig(level=logging.INFO, format=log_format, datefmt=log_datefmt) working_dir = None if args.input_file == '-' or args.stdin: # force stdin payload = stdin elif not args.input_file and stdin.isatty(): # no force, empty stdin parser.print_help() exit() elif not args.input_file: # no file -> default stdin payload = stdin else: # must have specified normal input_file payload = open(args.input_file) working_dir = os.path.dirname(args.input_file) if args.no_chdir: working_dir = None if args.profile_dir: profile_dir = os.path.expanduser(args.profile_dir) else: profile_dir = None logging.info('Reading notebook %s', payload.name) nb = read(payload, 'json') nb_runner = NotebookRunner(nb, args.pylab, args.matplotlib, profile_dir, working_dir) exit_status = 0 try: nb_runner.run_notebook(skip_exceptions=args.skip_exceptions) except NotebookError: exit_status = 1 if args.output_file and args.output_file != '-': logging.info('Saving to %s', args.output_file) write(nb_runner.nb, open(args.output_file, 'w'), 'json') if args.stdout or args.output_file == '-': write(nb_runner.nb, stdout, 'json') print() if args.html is not False: if args.html is None: # if --html is given but no filename is provided, # come up with a sane output name based on the # input filename if args.input_file.endswith('.ipynb'): args.html = args.input_file[:-6] + '.html' else: args.html = args.input_file + '.html' if args.template is False: exporter = HTMLExporter() else: exporter = HTMLExporter( config=Config({'HTMLExporter':{'template_file':args.template, 'template_path': ['.', '/']}})) logging.info('Saving HTML snapshot to %s' % args.html) output, resources = exporter.from_notebook_node(nb_runner.nb) codecs.open(args.html, 'w', encoding='utf-8').write(output) nb_runner.shutdown_kernel() if exit_status != 0: logging.warning('Exiting with nonzero exit status') exit(exit_status)
def runapp(nbname): err = "" # initialize error string returned by notebook app invocation -- required for exception messages try: nbpath = fetch_nb(nbname) except LookupError as ex: return (render_template("server_status.html", message="Cannot locate notebook app: " + nbname), 404) jinja_env = Environment(loader=PackageLoader('ipyapp', 'templates')) status = HTMLExporter(extra_loaders=[current_app.jinja_env.loader], template_file='server_status.html') try: options = dict(env=None, timeout=TIMEOUT, output=None, view=False, format=FORMAT) if request.method == 'GET': nbargs_dict = request.args.to_dict() else: # POST, so get from form nbargs_dict = request.form.to_dict() debug('options (before): %s' % options) debug('nbargs_dict (before): %s' % nbargs_dict) update_options_nbargs(options, nbargs_dict) debug('options (before): %s' % options) debug('nbargs_dict (before): %s' % nbargs_dict) info("notebook arguments:" + str(nbargs_dict)) if options['view']: # just view notebook, don't re-execute info("app view only") nbtxt = open(nbpath).read() name = basename(nbpath).replace('.ipynb', '') else: info("creating NotebookApp") nba = NotebookApp(nbpath, template="server_output.html", **options) name = nba.name info("nba.inputs: %s" % nba.inputs) info("nbargs_dict: %s" % nbargs_dict) if len(nba.inputs) > 0 and len( nba.inputs) > len(nbargs_dict) and request.method == "GET": info( "generate app form, since not enough inputs were provided") singles = { k: v for k, v in nba.inputs.iteritems() if v != "para" } multis = [k for k, v in nba.inputs.iteritems() if v == "para"] return (render_template( "form.html", nbapp=nba.name, desc=nba.desc, params=sorted(singles.items()), multiline=sorted(multis), ), 200) else: nba.set_nbargs(**nbargs_dict) (nbtxt, err) = nba.startapp() if options['format'] == 'html': Exporter = partial(HTMLExporter, extra_loaders=[current_app.jinja_env.loader], template_file="server_output.html") elif options['format'] == 'md' or options['format'] == 'markdown': Exporter = MarkdownExporter elif options['format'] == 'py' or options['format'] == 'python': Exporter = PythonExporter exporter = Exporter() nb_obj = nb_read_json(nbtxt) html, resources = exporter.from_notebook_node( nb_obj, resources=dict(nbapp=name)) return (html, 200) except (IOError, ValueError, NotebookAppFormatError) as ex: return (render_template("server_status.html", message="Notebook App [%s] invalid file" % nbpath, exception=ex, error=err), 501) except (BadRequestKeyError, KeyError, ValueError, TypeError) as ex: # TODO: tighten this up so invalid inputs are caught in a way that nba.name can be used return (render_template("server_status.html", message="Notebook App [%s] invalid inputs" % nbpath, exception=ex, error=err), 400) except NotebookAppExecutionError as ex: return (render_template("server_status.html", message='Notebook App [%s] failed to run' % nba.name, exception=ex, error=err), 400) except Exception as ex: return (render_template("server_status.html", message='Notebook App [%s] unknown error' % nbpath, exception=ex, error=err), 400)
def main(): # TODO: options: # - output: # - save HTML report (nbconvert) print 'ko' log_format = '%(asctime)s %(message)s' log_datefmt = '%m/%d/%Y %I:%M:%S %p' parser = argparse.ArgumentParser() parser.add_argument('input_file', help='.ipynb file to run') parser.add_argument('output_file', nargs='?', help='.ipynb file to save cell output to') parser.add_argument('--quiet', '-q', action='store_true', help='don\'t print anything unless things go wrong') parser.add_argument('--overwrite', '-o', action='store_true', help='write notebook output back to original notebook') parser.add_argument('--html', nargs='?', default=False, help='output an HTML snapshot of the notebook') parser.add_argument('--pylab', action='store_true', help='start notebook with pylab enabled') args = parser.parse_args() if args.overwrite: if args.output_file is not None: print >> stderr, 'Error: output_filename must not be provided if '\ '--overwrite (-o) given' exit(1) else: args.output_file = args.input_file if not args.quiet: logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=log_datefmt) nb_runner = NotebookRunner(args.input_file, args.pylab) exit_status = 0 try: nb_runner.run_notebook() except NotebookError: exit_status = 1 if args.output_file: nb_runner.save_notebook(args.output_file) if args.html is not False: if args.html is None: # if --html is given but no filename is provided, # come up with a sane output name based on the # input filename if args.input_file.endswith('.ipynb'): args.html = args.input_file[:-6] + '.html' else: args.html = args.input_file + '.ipynb' logging.info('Saving HTML snapshot to %s' % args.html) exporter = HTMLExporter() output, resources = exporter.from_notebook_node(nb_runner.nb) codecs.open(args.html, 'w', encoding='utf-8').write(output) if exit_status != 0: logging.warning('Exiting with nonzero exit status') exit(exit_status)
def main(): log_format = "%(asctime)s %(levelname)s: %(message)s" log_datefmt = "%m/%d/%Y %I:%M:%S %p" parser = argparse.ArgumentParser() parser.add_argument( "--version", "-v", action="version", version=runipy.__version__, help="print version information" ) parser.add_argument("input_file", nargs="?", help=".ipynb file to run (or stdin)") parser.add_argument("output_file", nargs="?", help=".ipynb file to save cell output to") parser.add_argument("--quiet", "-q", action="store_true", help="don't print anything unless things go wrong") parser.add_argument( "--overwrite", "-o", action="store_true", help="write notebook output back to original notebook" ) format_grp = parser.add_mutually_exclusive_group() format_grp.add_argument("--html", nargs="?", default=False, help="output an HTML snapshot of the notebook") format_grp.add_argument("--pdf", nargs="?", default=False, help="output a PDF snapshot of the notebook") parser.add_argument("--template", nargs="?", default=False, help="template to use for HTML output") parser.add_argument("--pylab", action="store_true", help="start notebook with pylab enabled") parser.add_argument("--matplotlib", action="store_true", help="start notebook with matplotlib inlined") parser.add_argument( "--skip-exceptions", "-s", action="store_true", help="if an exception occurs in a cell," + " continue running the subsequent cells", ) parser.add_argument("--stdout", action="store_true", help="print notebook to stdout (or use - as output_file") parser.add_argument("--stdin", action="store_true", help="read notebook from stdin (or use - as input_file)") parser.add_argument( "--no-chdir", action="store_true", help="do not change directory to notebook's at kernel startup" ) parser.add_argument("--profile-dir", help="set the profile location directly") args = parser.parse_args() if args.overwrite: if args.output_file is not None: print("Error: output_filename must not be provided if " "--overwrite (-o) given", file=stderr) exit(1) else: args.output_file = args.input_file if not args.quiet: logging.basicConfig(level=logging.INFO, format=log_format, datefmt=log_datefmt) working_dir = None payload_source = "" payload = "" if args.input_file == "-" or args.stdin: # force stdin payload_source = stdin.name payload = stdin.read() elif not args.input_file and stdin.isatty(): # no force, empty stdin parser.print_help() exit() elif not args.input_file: # no file -> default stdin payload_source = stdin.name payload = stdin.read() else: # must have specified normal input_file with open(args.input_file) as input_file: payload_source = input_file.name payload = input_file.read() working_dir = os.path.dirname(args.input_file) if args.no_chdir: working_dir = None if args.profile_dir: profile_dir = os.path.expanduser(args.profile_dir) else: profile_dir = None logging.info("Reading notebook %s", payload_source) try: # Ipython 3 nb = reads(payload, 3) except (TypeError, NBFormatError): # Ipython 2 nb = reads(payload, "json") nb_runner = NotebookRunner(nb, args.pylab, args.matplotlib, profile_dir, working_dir) exit_status = 0 try: nb_runner.run_notebook(skip_exceptions=args.skip_exceptions) except NotebookError: exit_status = 1 if args.output_file and args.output_file != "-": logging.info("Saving to %s", args.output_file) with open(args.output_file, "w") as output_filehandle: try: # Ipython 3 write(nb_runner.nb, output_filehandle, 3) except (TypeError, NBFormatError): # Ipython 2 write(nb_runner.nb, output_filehandle, "json") if args.stdout or args.output_file == "-": try: # Ipython 3 write(nb_runner.nb, stdout, 3) except (TypeError, NBFormatError): # Ipython 2 write(nb_runner.nb, stdout, "json") print() if args.html is not False: if args.html is None: # if --html is given but no filename is provided, # come up with a sane output name based on the # input filename if args.input_file.endswith(".ipynb"): args.html = args.input_file[:-6] + ".html" else: args.html = args.input_file + ".html" if args.template is False: exporter = HTMLExporter() else: exporter = HTMLExporter( config=Config({"HTMLExporter": {"template_file": args.template, "template_path": [".", "/"]}}) ) logging.info("Saving HTML snapshot to %s" % args.html) output, resources = exporter.from_notebook_node(convert(nb_runner.nb, current_nbformat)) codecs.open(args.html, "w", encoding="utf-8").write(output) elif args.pdf is not False: if args.pdf is None: # if --html is given but no filename is provided, # come up with a sane output name based on the # input filename if args.input_file.endswith(".ipynb"): args.pdf = args.input_file[:-6] + ".pdf" else: args.pdf = args.input_file + ".pdf" if args.template is False: exporter = PDFExporter() else: exporter = PDFExporter( config=Config({"PDFExporter": {"template_file": args.template, "template_path": [".", "/"]}}) ) logging.info("Saving PDF snapshot to %s" % args.pdf) output, resources = exporter.from_notebook_node(convert(nb_runner.nb, current_nbformat)) writer = FilesWriter() writer.build_directory = os.path.dirname(args.pdf) writer.write(output, resources, os.path.splitext(os.path.basename(args.pdf))[0]) nb_runner.shutdown_kernel() if exit_status != 0: logging.warning("Exiting with nonzero exit status") exit(exit_status)
def main(): log_format = '%(asctime)s %(message)s' log_datefmt = '%m/%d/%Y %I:%M:%S %p' parser = argparse.ArgumentParser() parser.add_argument('input_file', help='.ipynb file to run') parser.add_argument('output_file', nargs='?', help='.ipynb file to save cell output to') parser.add_argument('--quiet', '-q', action='store_true', help='don\'t print anything unless things go wrong') parser.add_argument('--overwrite', '-o', action='store_true', help='write notebook output back to original notebook') parser.add_argument('--html', nargs='?', default=False, help='output an HTML snapshot of the notebook') parser.add_argument('--template', nargs='?', default=False, help='template to use for HTML output') parser.add_argument('--pylab', action='store_true', help='start notebook with pylab enabled') parser.add_argument('--matplotlib', action='store_true', help='start notebook with matplotlib inlined') parser.add_argument( '--skip-exceptions', '-s', action='store_true', help= 'if an exception occurs in a cell, continue running the subsequent cells' ) args = parser.parse_args() if args.overwrite: if args.output_file is not None: print( 'Error: output_filename must not be provided if ' '--overwrite (-o) given', file=stderr) exit(1) else: args.output_file = args.input_file if not args.quiet: logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=log_datefmt) nb_runner = NotebookRunner(args.input_file, args.pylab, args.matplotlib) exit_status = 0 try: nb_runner.run_notebook(skip_exceptions=args.skip_exceptions) except NotebookError: exit_status = 1 if args.output_file: nb_runner.save_notebook(args.output_file) if args.html is not False: if args.html is None: # if --html is given but no filename is provided, # come up with a sane output name based on the # input filename if args.input_file.endswith('.ipynb'): args.html = args.input_file[:-6] + '.html' else: args.html = args.input_file + '.ipynb' if args.template is False: exporter = HTMLExporter() else: exporter = HTMLExporter(config=Config( {'HTMLExporter': { 'default_template': args.template }})) logging.info('Saving HTML snapshot to %s' % args.html) output, resources = exporter.from_notebook_node(nb_runner.nb) codecs.open(args.html, 'w', encoding='utf-8').write(output) if exit_status != 0: logging.warning('Exiting with nonzero exit status') exit(exit_status)