本文整理汇总了Python中IPython.terminal.interactiveshell.TerminalInteractiveShell类的典型用法代码示例。如果您正苦于以下问题:Python TerminalInteractiveShell类的具体用法?Python TerminalInteractiveShell怎么用?Python TerminalInteractiveShell使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TerminalInteractiveShell类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, color_scheme=None, completekey=None, stdin=None, stdout=None, context=5):
# Parent constructor:
try:
self.context = int(context)
if self.context <= 0:
raise ValueError("Context must be a positive integer")
except (TypeError, ValueError):
raise ValueError("Context must be a positive integer")
OldPdb.__init__(self, completekey, stdin, stdout)
# IPython changes...
self.shell = get_ipython()
if self.shell is None:
# No IPython instance running, we must create one
from IPython.terminal.interactiveshell import TerminalInteractiveShell
self.shell = TerminalInteractiveShell.instance()
if color_scheme is not None:
warnings.warn("The `color_scheme` argument is deprecated since version 5.1", DeprecationWarning)
else:
color_scheme = self.shell.colors
self.aliases = {}
# Create color table: we copy the default one from the traceback
# module and add a few attributes needed for debugging
self.color_scheme_table = exception_colors()
# shorthands
C = coloransi.TermColors
cst = self.color_scheme_table
cst["NoColor"].colors.prompt = C.NoColor
cst["NoColor"].colors.breakpoint_enabled = C.NoColor
cst["NoColor"].colors.breakpoint_disabled = C.NoColor
cst["Linux"].colors.prompt = C.Green
cst["Linux"].colors.breakpoint_enabled = C.LightRed
cst["Linux"].colors.breakpoint_disabled = C.Red
cst["LightBG"].colors.prompt = C.Blue
cst["LightBG"].colors.breakpoint_enabled = C.LightRed
cst["LightBG"].colors.breakpoint_disabled = C.Red
cst["Neutral"].colors.prompt = C.Blue
cst["Neutral"].colors.breakpoint_enabled = C.LightRed
cst["Neutral"].colors.breakpoint_disabled = C.Red
self.set_colors(color_scheme)
# Add a python parser so we can syntax highlight source while
# debugging.
self.parser = PyColorize.Parser()
# Set the prompt - the default prompt is '(Pdb)'
self.prompt = prompt
示例2: run_ipython_shell_v11
def run_ipython_shell_v11(locals, globals, first_time):
'''IPython shell from IPython version 0.11'''
if first_time:
banner = "Hit Ctrl-D to return to PuDB."
else:
banner = ""
try:
# IPython 1.0 got rid of the frontend intermediary, and complains with
# a deprecated warning when you use it.
from IPython.terminal.interactiveshell import TerminalInteractiveShell
from IPython.terminal.ipapp import load_default_config
except ImportError:
from IPython.frontend.terminal.interactiveshell import \
TerminalInteractiveShell
from IPython.frontend.terminal.ipapp import load_default_config
# XXX: in the future it could be useful to load a 'pudb' config for the
# user (if it exists) that could contain the user's macros and other
# niceities.
config = load_default_config()
shell = TerminalInteractiveShell.instance(config=config,
banner2=banner)
# XXX This avoids a warning about not having unique session/line numbers.
# See the HistoryManager.writeout_cache method in IPython.core.history.
shell.history_manager.new_session()
# Save the originating namespace
old_locals = shell.user_ns
old_globals = shell.user_global_ns
# Update shell with current namespace
_update_ns(shell, locals, globals)
shell.mainloop(banner)
# Restore originating namespace
_update_ns(shell, old_locals, old_globals)
示例3: get_python_console
def get_python_console(namespace=None):
"""
Return a interactive python console instance with caller's stack
"""
if namespace is None:
import inspect
frame = inspect.currentframe()
caller = frame.f_back
if not caller:
logging.error("can't find caller who start this console.")
caller = frame
namespace = dict(caller.f_globals)
namespace.update(caller.f_locals)
try:
from IPython.terminal.interactiveshell import TerminalInteractiveShell
shell = TerminalInteractiveShell(user_ns=namespace)
except ImportError:
try:
import readline
import rlcompleter
readline.set_completer(rlcompleter.Completer(namespace).complete)
readline.parse_and_bind("tab: complete")
except ImportError:
pass
import code
shell = code.InteractiveConsole(namespace)
shell._quit = False
def exit():
shell._quit = True
def readfunc(prompt=""):
if shell._quit:
raise EOFError
return six.moves.input(prompt)
# inject exit method
shell.ask_exit = exit
shell.raw_input = readfunc
return shell
示例4: init_shell
def init_shell(self):
banner1 = 'Umeng development shell, do whatever you want.\n' if DEVELOP_MODE else \
'Umeng production shell, use it carefully!\n'
self.shell = TerminalInteractiveShell.instance(config=self.config,
display_banner=False, profile_dir=self.profile_dir,
ipython_dir=self.ipython_dir, banner1=banner1, banner2='')
self.shell.configurables.append(self)
示例5: __init__
def __init__(self,color_scheme='NoColor',completekey=None,
stdin=None, stdout=None, context=5):
# Parent constructor:
try:
self.context=int(context)
if self.context <= 0:
raise ValueError("Context must be a positive integer")
except (TypeError, ValueError):
raise ValueError("Context must be a positive integer")
OldPdb.__init__(self,completekey,stdin,stdout)
# IPython changes...
self.shell = get_ipython()
if self.shell is None:
# No IPython instance running, we must create one
from IPython.terminal.interactiveshell import \
TerminalInteractiveShell
self.shell = TerminalInteractiveShell.instance()
self.aliases = {}
# Create color table: we copy the default one from the traceback
# module and add a few attributes needed for debugging
self.color_scheme_table = exception_colors()
# shorthands
C = coloransi.TermColors
cst = self.color_scheme_table
cst['NoColor'].colors.prompt = C.NoColor
cst['NoColor'].colors.breakpoint_enabled = C.NoColor
cst['NoColor'].colors.breakpoint_disabled = C.NoColor
cst['Linux'].colors.prompt = C.Green
cst['Linux'].colors.breakpoint_enabled = C.LightRed
cst['Linux'].colors.breakpoint_disabled = C.Red
cst['LightBG'].colors.prompt = C.Blue
cst['LightBG'].colors.breakpoint_enabled = C.LightRed
cst['LightBG'].colors.breakpoint_disabled = C.Red
self.set_colors(color_scheme)
# Add a python parser so we can syntax highlight source while
# debugging.
self.parser = PyColorize.Parser()
# Set the prompt - the default prompt is '(Pdb)'
Colors = cst.active_colors
if color_scheme == 'NoColor':
self.prompt = prompt
else:
# The colour markers are wrapped by bytes 01 and 02 so that readline
# can calculate the width.
self.prompt = u'\x01%s\x02%s\x01%s\x02' % (Colors.prompt, prompt, Colors.Normal)
示例6: main
def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cto_tree.settings")
try:
if len(sys.argv) >= 2 and sys.argv[1] == '--plain':
raise ImportError
user_ns = locals()
if has_ushell:
app = UmengIPythonApp.instance()
app.initialize()
app.shell.user_ns.update(user_ns)
sys.exit(app.start())
else:
from IPython.terminal.interactiveshell import TerminalInteractiveShell
shell = TerminalInteractiveShell(user_ns=user_ns)
shell.mainloop()
except ImportError:
import code
shell = code.InteractiveConsole(locals=locals())
shell.interact()
示例7: init_shell
def init_shell(self):
self.shell = TerminalInteractiveShell.instance(
config=self.config,
display_banner=False,
profile_dir=self.profile_dir,
ipython_dir=self.ipython_dir,
banner1=get_banner(),
banner2=''
)
self.shell.configurables.append(self)
示例8: init_shell
def init_shell(self):
"""initialize the InteractiveShell instance"""
# Create an InteractiveShell instance.
# shell.display_banner should always be False for the terminal
# based app, because we call shell.show_banner() by hand below
# so the banner shows *before* all extension loading stuff.
self.shell = TerminalInteractiveShell.instance(parent=self,
display_banner=False, profile_dir=self.profile_dir,
ipython_dir=self.ipython_dir, user_ns=self.user_ns)
self.shell.configurables.append(self)
示例9: raw_input
def raw_input(self, *args, **kw):
try:
return TerminalInteractiveShell.raw_input(self,
*args, **kw) # needs decoding (see below)?
except EOFError:
r = raw_input("Do you wish to commit your "
"database changes? [yes]")
if not r.lower().startswith("n"):
if using_sqlalchemy:
self.push("session.flush()")
else:
self.push("hub.commit()")
raise EOFError
示例10: main
def main():
"""Use quickstart to ensure we have correct env, then execute imports in ipython and done."""
quickstart.main(quickstart.parser.parse_args(['--mk-virtualenv', sys.prefix]))
print('Welcome to IPython designed for running CFME QE code.')
ipython = TerminalInteractiveShell.instance()
for code_import in IMPORTS:
print('> {}'.format(code_import))
ipython.run_cell(code_import)
from cfme.utils.path import conf_path
custom_import_path = conf_path.join('miq_python_startup.py')
if custom_import_path.exists():
with open(custom_import_path.strpath, 'r') as custom_import_file:
custom_import_code = custom_import_file.read()
print('Importing custom code:\n{}'.format(custom_import_code.strip()))
ipython.run_cell(custom_import_code)
else:
print(
'You can create your own python file with imports you use frequently. '
'Just create a conf/miq_python_startup.py file in your repo. '
'This file can contain arbitrary python code that is executed in this context.')
ipython.interact()
示例11: interactive
def interactive(idx=0, DongleClass=RfCat, intro=''):
global d
import rflib.chipcon_nic as rfnic
import atexit
d = DongleClass(idx=idx)
d.setModeRX() # this puts the dongle into receive mode
atexit.register(cleanupInteractiveAtExit)
gbls = globals()
lcls = locals()
try:
import IPython.Shell
ipsh = IPython.Shell.IPShell(argv=[''], user_ns=lcls, user_global_ns=gbls)
print intro
ipsh.mainloop(intro)
except ImportError, e:
try:
from IPython.terminal.interactiveshell import TerminalInteractiveShell
ipsh = TerminalInteractiveShell()
ipsh.user_global_ns.update(gbls)
ipsh.user_global_ns.update(lcls)
ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart!
ipsh.mainloop(intro)
except ImportError, e:
try:
from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
ipsh = TerminalInteractiveShell()
ipsh.user_global_ns.update(gbls)
ipsh.user_global_ns.update(lcls)
ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart!
ipsh.mainloop(intro)
except ImportError, e:
print e
shell = code.InteractiveConsole(gbls)
shell.interact(intro)
示例12: interactive
def interactive(port='/dev/ttyACM0', InterfaceClass=CanInterface, intro='', load_filename=None):
global c
import atexit
c = InterfaceClass(port=port, load_filename=load_filename)
atexit.register(cleanupInteractiveAtExit)
gbls = globals()
lcls = locals()
try:
import IPython.Shell
ipsh = IPython.Shell.IPShell(argv=[''], user_ns=lcls, user_global_ns=gbls)
print intro
ipsh.mainloop(intro)
except ImportError, e:
try:
from IPython.terminal.interactiveshell import TerminalInteractiveShell
ipsh = TerminalInteractiveShell()
ipsh.user_global_ns.update(gbls)
ipsh.user_global_ns.update(lcls)
ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart!
ipsh.mainloop(intro)
except ImportError, e:
try:
from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
ipsh = TerminalInteractiveShell()
ipsh.user_global_ns.update(gbls)
ipsh.user_global_ns.update(lcls)
ipsh.autocall = 2 # don't require parenthesis around *everything*. be smart!
ipsh.mainloop(intro)
except ImportError, e:
print e
shell = code.InteractiveConsole(gbls)
shell.interact(intro)
示例13: __init__
def __init__(self, *args, **kwargs):
#Initialization based on: from IPython.testing.globalipapp import start_ipython
self._curr_exec_line = 0
# Store certain global objects that IPython modifies
_displayhook = sys.displayhook
_excepthook = sys.excepthook
# Create and initialize our IPython instance.
shell = TerminalInteractiveShell.instance()
shell.showtraceback = _showtraceback
# IPython is ready, now clean up some global state...
# Deactivate the various python system hooks added by ipython for
# interactive convenience so we don't confuse the doctest system
sys.displayhook = _displayhook
sys.excepthook = _excepthook
# So that ipython magics and aliases can be doctested (they work by making
# a call into a global _ip object). Also make the top-level get_ipython
# now return this without recursively calling here again.
get_ipython = shell.get_ipython
try:
import __builtin__
except:
import builtins as __builtin__
__builtin__._ip = shell
__builtin__.get_ipython = get_ipython
# We want to print to stdout/err as usual.
io.stdout = original_stdout
io.stderr = original_stderr
self._curr_exec_lines = []
self.ipython = shell
示例14: start_ipython
def start_ipython():
"""Start a global IPython shell, which we need for IPython-specific syntax.
"""
global get_ipython
# This function should only ever run once!
if hasattr(start_ipython, 'already_called'):
return
start_ipython.already_called = True
# Store certain global objects that IPython modifies
_displayhook = sys.displayhook
_excepthook = sys.excepthook
_main = sys.modules.get('__main__')
# Create custom argv and namespaces for our IPython to be test-friendly
config = tools.default_config()
# Create and initialize our test-friendly IPython instance.
shell = TerminalInteractiveShell.instance(config=config,
)
# A few more tweaks needed for playing nicely with doctests...
# remove history file
shell.tempfiles.append(config.HistoryManager.hist_file)
# These traps are normally only active for interactive use, set them
# permanently since we'll be mocking interactive sessions.
shell.builtin_trap.activate()
# Modify the IPython system call with one that uses getoutput, so that we
# can capture subcommands and print them to Python's stdout, otherwise the
# doctest machinery would miss them.
shell.system = py3compat.MethodType(xsys, shell)
shell._showtraceback = py3compat.MethodType(_showtraceback, shell)
# IPython is ready, now clean up some global state...
# Deactivate the various python system hooks added by ipython for
# interactive convenience so we don't confuse the doctest system
sys.modules['__main__'] = _main
sys.displayhook = _displayhook
sys.excepthook = _excepthook
# So that ipython magics and aliases can be doctested (they work by making
# a call into a global _ip object). Also make the top-level get_ipython
# now return this without recursively calling here again.
_ip = shell
get_ipython = _ip.get_ipython
builtin_mod._ip = _ip
builtin_mod.get_ipython = get_ipython
# To avoid extra IPython messages during testing, suppress io.stdout/stderr
io.stdout = StreamProxy('stdout')
io.stderr = StreamProxy('stderr')
# Override paging, so we don't require user interaction during the tests.
def nopage(strng, start=0, screen_lines=0, pager_cmd=None):
print(strng)
page.orig_page = page.page
page.page = nopage
return _ip
示例15: __init__
def __init__(self, color_scheme="NoColor", completekey=None, stdin=None, stdout=None):
# Parent constructor:
if has_pydb and completekey is None:
OldPdb.__init__(self, stdin=stdin, stdout=io.stdout)
else:
OldPdb.__init__(self, completekey, stdin, stdout)
# IPython changes...
self.is_pydb = has_pydb
self.shell = get_ipython()
if self.shell is None:
# No IPython instance running, we must create one
from IPython.terminal.interactiveshell import TerminalInteractiveShell
self.shell = TerminalInteractiveShell.instance()
if self.is_pydb:
# interactiveshell.py's ipalias seems to want pdb's checkline
# which located in pydb.fn
import pydb.fns
self.checkline = lambda filename, lineno: pydb.fns.checkline(self, filename, lineno)
self.curframe = None
self.do_restart = self.new_do_restart
self.old_all_completions = self.shell.Completer.all_completions
self.shell.Completer.all_completions = self.all_completions
self.do_list = decorate_fn_with_doc(self.list_command_pydb, OldPdb.do_list)
self.do_l = self.do_list
self.do_frame = decorate_fn_with_doc(self.new_do_frame, OldPdb.do_frame)
self.aliases = {}
# Create color table: we copy the default one from the traceback
# module and add a few attributes needed for debugging
self.color_scheme_table = exception_colors()
# shorthands
C = coloransi.TermColors
cst = self.color_scheme_table
cst["NoColor"].colors.prompt = C.NoColor
cst["NoColor"].colors.breakpoint_enabled = C.NoColor
cst["NoColor"].colors.breakpoint_disabled = C.NoColor
cst["Linux"].colors.prompt = C.Green
cst["Linux"].colors.breakpoint_enabled = C.LightRed
cst["Linux"].colors.breakpoint_disabled = C.Red
cst["LightBG"].colors.prompt = C.Blue
cst["LightBG"].colors.breakpoint_enabled = C.LightRed
cst["LightBG"].colors.breakpoint_disabled = C.Red
self.set_colors(color_scheme)
# Add a python parser so we can syntax highlight source while
# debugging.
self.parser = PyColorize.Parser()
# Set the prompt
Colors = cst.active_colors
self.prompt = u"%s%s%s" % (Colors.prompt, prompt, Colors.Normal) # The default prompt is '(Pdb)'