def prompt():
     prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
     lines = [input(prompt_text)]
     prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
     while self.check_complete('\n'.join(lines))[0] == 'incomplete':
         lines.append( input(prompt_continuation) )
     return '\n'.join(lines)
Esempio n. 2
0
 def call_editor(self, filename, line=0):
     if line is None:
         line = 0
     cmd = template.format(filename=pipes.quote(filename), line=line)
     print(">", cmd)
     proc = subprocess.Popen(cmd, shell=True)
     if wait and proc.wait() != 0:
         raise TryNext()
     if wait:
         py3compat.input("Press Enter when done editing:")
Esempio n. 3
0
    def __call__(self, etype, evalue, etb):
        """Handle an exception, call for compatible with sys.excepthook"""
        
        # do not allow the crash handler to be called twice without reinstalling it
        # this prevents unlikely errors in the crash handling from entering an
        # infinite loop.
        sys.excepthook = sys.__excepthook__
        
        # Report tracebacks shouldn't use color in general (safer for users)
        color_scheme = 'NoColor'

        # Use this ONLY for developer debugging (keep commented out for release)
        #color_scheme = 'Linux'   # dbg
        try:
            rptdir = self.app.ipython_dir
        except:
            rptdir = os.getcwdu()
        if rptdir is None or not os.path.isdir(rptdir):
            rptdir = os.getcwdu()
        report_name = os.path.join(rptdir,self.crash_report_fname)
        # write the report filename into the instance dict so it can get
        # properly expanded out in the user message template
        self.crash_report_fname = report_name
        self.info['crash_report_fname'] = report_name
        TBhandler = ultratb.VerboseTB(
            color_scheme=color_scheme,
            long_header=1,
            call_pdb=self.call_pdb,
        )
        if self.call_pdb:
            TBhandler(etype,evalue,etb)
            return
        else:
            traceback = TBhandler.text(etype,evalue,etb,context=31)

        # print traceback to screen
        if self.show_crash_traceback:
            print(traceback, file=sys.stderr)

        # and generate a complete report on disk
        try:
            report = open(report_name,'w')
        except:
            print('Could not create crash report on disk.', file=sys.stderr)
            return

        # Inform user on stderr of what happened
        print('\n'+'*'*70+'\n', file=sys.stderr)
        print(self.message_template.format(**self.info), file=sys.stderr)

        # Construct report on disk
        report.write(self.make_report(traceback))
        report.close()
        input("Hit <Enter> to quit (your terminal may close):")
Esempio n. 4
0
 def call_editor(self, filename, line=0):
     if line is None:
         line = 0
     cmd = template.format(filename=pipes.quote(filename), line=line)
     print(">", cmd)
     # pipes.quote doesn't work right on Windows, but it does after splitting
     if sys.platform.startswith('win'):
         cmd = shlex.split(cmd)
     proc = subprocess.Popen(cmd, shell=True)
     if wait and proc.wait() != 0:
         raise TryNext()
     if wait:
         py3compat.input("Press Enter when done editing:")
Esempio n. 5
0
def slide(file_path, noclear=False, format_rst=True, formatter="terminal",
          style="native", auto_all=False, delimiter='...'):
    if noclear:
        demo_class = Demo
    else:
        demo_class = ClearDemo
    demo = demo_class(file_path, format_rst=format_rst, formatter=formatter,
                      style=style, auto_all=auto_all)
    while not demo.finished:
        demo()
        try:
            py3compat.input('\n' + delimiter)
        except KeyboardInterrupt:
            exit(1)
Esempio n. 6
0
def snip_print(str,width = 75,print_full = 0,header = ''):
    """Print a string snipping the midsection to fit in width.

    print_full: mode control:
    
      - 0: only snip long strings
      - 1: send to page() directly.
      - 2: snip long strings and ask for full length viewing with page()
    
    Return 1 if snipping was necessary, 0 otherwise."""

    if print_full == 1:
        page(header+str)
        return 0

    print(header, end=' ')
    if len(str) < width:
        print(str)
        snip = 0
    else:
        whalf = int((width -5)/2)
        print(str[:whalf] + ' <...> ' + str[-whalf:])
        snip = 1
    if snip and print_full == 2:
        if py3compat.input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
            page(str)
    return snip
Esempio n. 7
0
 def handle_stdin_request(self, msg_id, timeout=0.1):
     """ Method to capture raw_input
     """
     msg_rep = self.client.stdin_channel.get_msg(timeout=timeout)
     # in case any iopub came while we were waiting:
     self.handle_iopub(msg_id)
     if msg_id == msg_rep["parent_header"].get("msg_id"):
         # wrap SIGINT handler
         real_handler = signal.getsignal(signal.SIGINT)
         def double_int(sig,frame):
             # call real handler (forwards sigint to kernel),
             # then raise local interrupt, stopping local raw_input
             real_handler(sig,frame)
             raise KeyboardInterrupt
         signal.signal(signal.SIGINT, double_int)
         
         try:
             raw_data = input(msg_rep["content"]["prompt"])
         except EOFError:
             # turn EOFError into EOF character
             raw_data = '\x04'
         except KeyboardInterrupt:
             sys.stdout.write('\n')
             return
         finally:
             # restore SIGINT handler
             signal.signal(signal.SIGINT, real_handler)
         
         # only send stdin reply if there *was not* another request
         # or execution finished while we were reading.
         if not (self.client.stdin_channel.msg_ready() or self.client.shell_channel.msg_ready()):
             self.client.stdin_channel.input(raw_data)
Esempio n. 8
0
def ask_yes_no(prompt, default=None, interrupt=None):
    """Asks a question and returns a boolean (y/n) answer.

    If default is given (one of 'y','n'), it is used if the user input is
    empty. If interrupt is given (one of 'y','n'), it is used if the user
    presses Ctrl-C. Otherwise the question is repeated until an answer is
    given.

    An EOF is treated as the default answer.  If there is no default, an
    exception is raised to prevent infinite loops.

    Valid answers are: y/yes/n/no (match is not case sensitive)."""

    answers = {'y': True, 'n': False, 'yes': True, 'no': False}
    ans = None
    while ans not in answers.keys():
        try:
            ans = input(prompt + ' ').lower()
            if not ans:  # response was an empty string
                ans = default
        except KeyboardInterrupt:
            if interrupt:
                ans = interrupt
        except EOFError:
            if default in answers.keys():
                ans = default
                print()
            else:
                raise

    return answers[ans]
Esempio n. 9
0
 def prompt():
     isp = self.input_splitter
     prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
     prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
     while isp.push_accepts_more():
         line = cast_unicode_py2(input(prompt_text))
         isp.push(line)
         prompt_text = prompt_continuation
     return isp.source_reset()
Esempio n. 10
0
    def __call__(self, index=None):
        """run a block of the demo.

        If index is given, it should be an integer >=1 and <= nblocks.  This
        means that the calling convention is one off from typical Python
        lists.  The reason for the inconsistency is that the demo always
        prints 'Block n/N, and N is the total, so it would be very odd to use
        zero-indexing here."""

        index = self._get_index(index)
        if index is None:
            return
        try:
            marquee = self.marquee
            next_block = self.src_blocks[index]
            self.block_index += 1
            if self._silent[index]:
                print(marquee('Executing silent block # %s (%s remaining)' %
                              (index, self.nblocks - index - 1)), file=io.stdout)
            else:
                self.pre_cmd()
                self.show(index)
                if self.auto_all or self._auto[index]:
                    print(marquee('output:'), file=io.stdout)
                else:
                    print(
                        marquee('Press <q> to quit, <Enter> to execute...'), end=' ', file=io.stdout)
                    ans = py3compat.input().strip()
                    if ans:
                        print(marquee('Block NOT executed'), file=io.stdout)
                        return
            try:
                save_argv = sys.argv
                sys.argv = self.sys_argv
                self.run_cell(next_block)
                self.post_cmd()
            finally:
                sys.argv = save_argv

        except:
            self.ip_showtb(filename=self.fname)
        else:
            self.ip_ns.update(self.user_ns)

        if self.block_index == self.nblocks:
            mq1 = self.marquee('END OF DEMO')
            if mq1:
                # avoid spurious print >>io.stdout,s if empty marquees are used
                print(file=io.stdout)
                print(mq1, file=io.stdout)
                print(
                    self.marquee('Use <demo_name>.reset() if you want to rerun it.'), file=io.stdout)
            self.finished = True
Esempio n. 11
0
 def prompt():
     return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
Esempio n. 12
0
    from IPython.core.inputsplitter import IPythonInputSplitter

    # configure here the syntax to use, prompt and whether to autoindent
    #isp, start_prompt = InputSplitter(), '>>> '
    isp, start_prompt = IPythonInputSplitter(), 'In> '

    autoindent = True
    #autoindent = False

    try:
        while True:
            prompt = start_prompt
            while isp.push_accepts_more():
                indent = ' '*isp.indent_spaces
                if autoindent:
                    line = indent + input(prompt+indent)
                else:
                    line = input(prompt)
                isp.push(line)
                prompt = '... '

            # Here we just return input so we can use it in a test suite, but a
            # real interpreter would instead send it for execution somewhere.
            #src = isp.source; raise EOFError # dbg
            raw = isp.source_raw
            src = isp.source_reset()
            print('Input source was:\n', src)
            print('Raw source was:\n', raw)
    except EOFError:
        print('Bye')
Esempio n. 13
0
 def page_more():
     ans = py3compat.input('---Return to continue, q to quit--- ')
     if ans.lower().startswith('q'):
         return False
     else:
         return True
 def prompt():
     return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
Esempio n. 15
0
 def page_more():
     ans = py3compat.input("---Return to continue, q to quit--- ")
     if ans.lower().startswith("q"):
         return False
     else:
         return True
Esempio n. 16
0
    from IPython.core.inputsplitter import IPythonInputSplitter

    # configure here the syntax to use, prompt and whether to autoindent
    #isp, start_prompt = InputSplitter(), '>>> '
    isp, start_prompt = IPythonInputSplitter(), 'In> '

    autoindent = True
    #autoindent = False

    try:
        while True:
            prompt = start_prompt
            while isp.push_accepts_more():
                indent = ' '*isp.get_indent_spaces()
                if autoindent:
                    line = indent + input(prompt+indent)
                else:
                    line = input(prompt)
                isp.push(line)
                prompt = '... '

            # Here we just return input so we can use it in a test suite, but a
            # real interpreter would instead send it for execution somewhere.
            #src = isp.source; raise EOFError # dbg
            raw = isp.source_raw
            src = isp.source_reset()
            print('Input source was:\n', src)
            print('Raw source was:\n', raw)
    except EOFError:
        print('Bye')