You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm trying to use ipython as a stand-in shell for interacting with a django server in a docker setup. When entering the shell via docker-compose exec <container> python manage.py shell -i ipython I'm being dropped in the ipython shell with the django context available. Everything then works properly, as long as I don't attempt to use tab (auto)completion. It worked just fine with all django instances in containers so far.
Specifically, attempting to Tab makes ipython not do anything (but stutter for a second), and crashes after manually completing the current command and pressing Enter.
On crashing, this cryptic error is being output (extended via the recommended %config Application.verbose_crash=True):
------------------------------------------------------------------------------------------------------------------------------------------------------TypeErrorPython3.6.15: /usr/local/bin/pythonThuSep2315:52:502021AproblemoccurredexecutingPythoncode. Hereisthesequenceoffunctioncallsleadinguptotheerror, withthemostrecent (innermost) calllast.
/usr/local/lib/python3.6/site-packages/IPython/terminal/ptutils.pyinget_completions(self=<IPython.terminal.ptutils.IPythonPTCompleterobject>, document=Document('from dwms.models import My', 26), complete_event=CompleteEvent(text_inserted=False, completion_requested=True))
112try:
-->113yieldfromself._get_completions(body, offset, cursor_position, self.ipy_completer)
self._get_completions=<functionIPythonPTCompleter._get_completionsat0x7f34f94c9268>body='from dwms.models import My'offset=26cursor_position=26self.ipy_completer=<IPython.core.completer.IPCompleterobjectat0x7f34af152be0>114exceptExceptionase:
/usr/local/lib/python3.6/site-packages/IPython/terminal/ptutils.pyin_get_completions(body='from dwms.models import My', offset=26, cursor_position=26, ipyc=<IPython.core.completer.IPCompleterobject>)
125body, ipyc.completions(body, offset))
-->126forcincompletions:
c=undefinedcompletions=<generatorobject_deduplicate_completionsat0x7f34aed8d200>127ifnotc.text:
/usr/local/lib/python3.6/site-packages/IPython/core/completer.pyin_deduplicate_completions(text='from dwms.models import My', completions=<generatorobjectIPCompleter.completions>)
437""-->438completions=list(completions)
completions=<generatorobjectIPCompleter.completionsat0x7f34aed8d1a8>globallist=undefined439ifnotcompletions:
/usr/local/lib/python3.6/site-packages/IPython/core/completer.pyincompletions(self=<IPython.core.completer.IPCompleterobject>, text='from dwms.models import My', offset=26)
1817try:
->1818forcinself._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
c=undefinedself._completions=<boundmethodIPCompleter._completionsof<IPython.core.completer.IPCompleterobjectat0x7f34af152be0>>text='from dwms.models import My'offset=26global_timeout=undefinedself.jedi_compute_type_timeout=4001819ifcand (cinseen):
/usr/local/lib/python3.6/site-packages/IPython/core/completer.pyin_completions(self=<IPython.core.completer.IPCompleterobject>, full_text='from dwms.models import My', offset=26, _timeout=0.4)
1861matched_text, matches, matches_origin, jedi_matches=self._complete(
->1862full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
full_text='from dwms.models import My'cursor_line=0globalcursor_pos=undefinedcursor_column=261863/usr/local/lib/python3.6/site-packages/IPython/core/completer.pyin_complete(self=<IPython.core.completer.IPCompleterobject>, cursor_line=0, cursor_pos=26, line_buffer='from dwms.models import My', text='My', full_text='from dwms.models import My')
2029completions=self._jedi_matches(
->2030cursor_pos, cursor_line, full_text)
cursor_pos=26cursor_line=0full_text='from dwms.models import My'2031/usr/local/lib/python3.6/site-packages/IPython/core/completer.pyin_jedi_matches(self=<IPython.core.completer.IPCompleterobject>, cursor_column=26, cursor_line=0, text='from dwms.models import My')
1373interpreter=jedi.Interpreter(
->1374text[:offset], namespaces, column=cursor_column, line=cursor_line+1)
text='from dwms.models import My'offset=26namespaces= [{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module'builtins' (built-in)>, '__builtins__': <module'builtins' (built-in)>, '_ih': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')"], '_oh': {}, '_dh': ['/app'], 'In': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')"], 'Out': {}, 'get_ipython': <boundmethodInteractiveShell.get_ipythonof<IPython.terminal.interactiveshell.TerminalInteractiveShellobjectat0x7f34af0e95c0>>, 'exit': <IPython.core.autocall.ExitAutocallobjectat0x7f34af1529b0>, 'quit': <IPython.core.autocall.ExitAutocallobjectat0x7f34af1529b0>, '_': '', '__': '', '___': '', '_i': '', '_ii': '', '_iii': '', '_i1': '%config Application.verbose_crash=True'}, {'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module'builtins' (built-in)>, '__builtins__': <module'builtins' (built-in)>, '_ih': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')"], '_oh': {}, '_dh': ['/app'], 'In': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')"], 'Out': {}, 'get_ipython': <boundmethodInteractiveShell.get_ipythonof<IPython.terminal.interactiveshell.TerminalInteractiveShellobjectat0x7f34af0e95c0>>, 'exit': <IPython.core.autocall.ExitAutocallobjectat0x7f34af1529b0>, 'quit': <IPython.core.autocall.ExitAutocallobjectat0x7f34af1529b0>, '_': '', '__': '', '___': '', '_i': '', '_ii': '', '_iii': '', '_i1': '%config Application.verbose_crash=True'}]
globalcolumn=undefinedcursor_column=26globalline=undefinedcursor_line=01375try_jedi=True/usr/local/lib/python3.6/site-packages/jedi/api/__init__.pyin__init__(self=<class'jedi.api.Interpreter'>instance, code='from dwms.models import My', namespaces=[{'In': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')"], 'Out': {}, '_': '', '__': '', '___': '', '__builtin__': <module'builtins' (built-in)>, '__builtins__': <module'builtins' (built-in)>, '__doc__': 'Automatically created module for IPython interactive environment', '__loader__': None, '__name__': '__main__', ...}, {'In': ['', "get_ipython().run_line_magic('config', 'Application.verbose_crash=True')"], 'Out': {}, '_': '', '__': '', '___': '', '__builtin__': <module'builtins' (built-in)>, '__builtins__': <module'builtins' (built-in)>, '__doc__': 'Automatically created module for IPython interactive environment', '__loader__': None, '__name__': '__main__', ...}], **kwds={'column': 26, 'line': 1})
725super().__init__(code, environment=environment,
-->726project=Project(Path.cwd()), **kwds)
globalproject=<module'jedi.api.project'from'/usr/local/lib/python3.6/site-packages/jedi/api/project.py'>globalProject=<class'jedi.api.project.Project'>globalPath.cwd=<boundmethodPath.cwdof<class'pathlib.Path'>>kwds= {'column': 26, 'line': 1}
727self.namespaces=namespacesTypeError: __init__() gotanunexpectedkeywordargument'column'Duringhandlingoftheaboveexception, anotherexceptionoccurred:
---------------------------------------------------------------------------AttributeErrorPython3.6.15: /usr/local/bin/pythonThuSep2315:52:502021AproblemoccurredexecutingPythoncode. Hereisthesequenceoffunctioncallsleadinguptotheerror, withthemostrecent (innermost) calllast.
/app/manage.pyin<module>7defmain():
8"""Run administrative tasks."""9os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dwms.settings')
10try:
11fromdjango.core.managementimportexecute_from_command_line12exceptImportErrorasexc:
13raiseImportError(
14"Couldn't import Django. Are you sure it's installed and "15"available on your PYTHONPATH environment variable? Did you "16"forget to activate a virtual environment?"17 ) fromexc18execute_from_command_line(sys.argv)
192021if__name__=='__main__':
--->22main()
globalmain=<functionmainat0x7f34fb589e18>/app/manage.pyinmain()
3importos4importsys567defmain():
8"""Run administrative tasks."""9os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dwms.settings')
10try:
11fromdjango.core.managementimportexecute_from_command_line12exceptImportErrorasexc:
13raiseImportError(
14"Couldn't import Django. Are you sure it's installed and "15"available on your PYTHONPATH environment variable? Did you "16"forget to activate a virtual environment?"17 ) fromexc--->18execute_from_command_line(sys.argv)
execute_from_command_line=<functionexecute_from_command_lineat0x7f34fa7ebe18>globalsys.argv= ['manage.py', 'shell', '-i', 'ipython']
192021if__name__=='__main__':
22main()
/usr/local/lib/python3.6/site-packages/django/core/management/__init__.pyinexecute_from_command_line(argv=['manage.py', 'shell', '-i', 'ipython'])
386else:
387self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
388# Special-cases: We want 'django-admin --version' and389# 'django-admin --help' to work, for backwards compatibility.390elifsubcommand=='version'orself.argv[1:] == ['--version']:
391sys.stdout.write(django.get_version() +'\n')
392elifself.argv[1:] in (['--help'], ['-h']):
393sys.stdout.write(self.main_help_text() +'\n')
394else:
395self.fetch_command(subcommand).run_from_argv(self.argv)
396397398defexecute_from_command_line(argv=None):
399"""Run a ManagementUtility."""400utility=ManagementUtility(argv)
-->401utility.execute()
utility.execute=<boundmethodManagementUtility.executeof<django.core.management.ManagementUtilityobjectat0x7f34fb4e25c0>>/usr/local/lib/python3.6/site-packages/django/core/management/__init__.pyinexecute(self=<django.core.management.ManagementUtilityobject>)
380381ifsubcommand=='help':
382if'--commands'inargs:
383sys.stdout.write(self.main_help_text(commands_only=True) +'\n')
384elifnotoptions.args:
385sys.stdout.write(self.main_help_text() +'\n')
386else:
387self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
388# Special-cases: We want 'django-admin --version' and389# 'django-admin --help' to work, for backwards compatibility.390elifsubcommand=='version'orself.argv[1:] == ['--version']:
391sys.stdout.write(django.get_version() +'\n')
392elifself.argv[1:] in (['--help'], ['-h']):
393sys.stdout.write(self.main_help_text() +'\n')
394else:
-->395self.fetch_command(subcommand).run_from_argv(self.argv)
self.fetch_command=<boundmethodManagementUtility.fetch_commandof<django.core.management.ManagementUtilityobjectat0x7f34fb4e25c0>>subcommand.run_from_argv=undefinedself.argv= ['manage.py', 'shell', '-i', 'ipython']
396397398defexecute_from_command_line(argv=None):
399"""Run a ManagementUtility."""400utility=ManagementUtility(argv)
401utility.execute()
/usr/local/lib/python3.6/site-packages/django/core/management/base.pyinrun_from_argv(self=<django.core.management.commands.shell.Commandobject>, argv=['manage.py', 'shell', '-i', 'ipython'])
315Setupanyenvironmentchangesrequested (e.g., Pythonpath316andDjangosettings), thenrunthiscommand. Ifthe317commandraisesa``CommandError``, interceptitandprintitsensibly318tostderr. Ifthe``--traceback``optionispresentortheraised319 ``Exception`` is not ``CommandError``, raiseit.
320""321self._called_from_command_line=True322parser=self.create_parser(argv[0], argv[1])
323324options=parser.parse_args(argv[2:])
325cmd_options=vars(options)
326# Move positional args out of options to mimic legacy optparse327args=cmd_options.pop('args', ())
328handle_default_options(options)
329try:
-->330self.execute(*args, **cmd_options)
self.execute=<boundmethodBaseCommand.executeof<django.core.management.commands.shell.Commandobjectat0x7f34fb3bf5c0>>args= ()
cmd_options= {'verbosity': 1, 'settings': None, 'pythonpath': None, 'traceback': False, 'no_color': False, 'force_color': False, 'no_startup': False, 'interface': 'ipython', 'command': None}
331exceptCommandErrorase:
332ifoptions.traceback:
333raise334335# SystemCheckError takes care of its own formatting.336ifisinstance(e, SystemCheckError):
337self.stderr.write(str(e), lambdax: x)
338else:
339self.stderr.write('%s: %s'% (e.__class__.__name__, e))
340sys.exit(e.returncode)
341finally:
342try:
343connections.close_all()
344exceptImproperlyConfigured:
345# Ignore if connections aren't setup at this point (e.g. no/usr/local/lib/python3.6/site-packages/django/core/management/base.pyinexecute(self=<django.core.management.commands.shell.Commandobject>, *args=(), **options={'command': None, 'force_color': False, 'interface': 'ipython', 'no_color': False, 'no_startup': False, 'pythonpath': None, 'settings': None, 'traceback': False, 'verbosity': 1})
356raiseCommandError("The --no-color and --force-color options can't be used together.")
357ifoptions['force_color']:
358self.style=color_style(force_color=True)
359elifoptions['no_color']:
360self.style=no_style()
361self.stderr.style_func=None362ifoptions.get('stdout'):
363self.stdout=OutputWrapper(options['stdout'])
364ifoptions.get('stderr'):
365self.stderr=OutputWrapper(options['stderr'])
366367ifself.requires_system_checksandnotoptions['skip_checks']:
368self.check()
369ifself.requires_migrations_checks:
370self.check_migrations()
-->371output=self.handle(*args, **options)
output=undefinedself.handle=<boundmethodCommand.handleof<django.core.management.commands.shell.Commandobjectat0x7f34fb3bf5c0>>args= ()
options= {'verbosity': 1, 'settings': None, 'pythonpath': None, 'traceback': False, 'no_color': False, 'force_color': False, 'no_startup': False, 'interface': 'ipython', 'command': None}
372ifoutput:
373ifself.output_transaction:
374connection=connections[options.get('database', DEFAULT_DB_ALIAS)]
375output='%s\n%s\n%s'% (
376self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()),
377output,
378self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()),
379 )
380self.stdout.write(output)
381returnoutput382383defcheck(self, app_configs=None, tags=None, display_num_errors=False,
384include_deployment_checks=False, fail_level=checks.ERROR,
385databases=None):
386""/usr/local/lib/python3.6/site-packages/django/core/management/commands/shell.pyinhandle(self=<django.core.management.commands.shell.Commandobject>, **options={'command': None, 'force_color': False, 'interface': 'ipython', 'no_color': False, 'no_startup': False, 'pythonpath': None, 'settings': None, 'traceback': False, 'verbosity': 1})
85# Execute the command and exit.86ifoptions['command']:
87exec(options['command'])
88return8990# Execute stdin if it has anything to read and exit.91# Not supported on Windows due to select.select() limitations.92ifsys.platform!='win32'andnotsys.stdin.isatty() andselect.select([sys.stdin], [], [], 0)[0]:
93exec(sys.stdin.read())
94return9596available_shells= [options['interface']] ifoptions['interface'] elseself.shells9798forshellinavailable_shells:
99try:
-->100returngetattr(self, shell)(options)
globalgetattr=undefinedself=<django.core.management.commands.shell.Commandobjectat0x7f34fb3bf5c0>shell='ipython'options= {'verbosity': 1, 'settings': None, 'pythonpath': None, 'traceback': False, 'no_color': False, 'force_color': False, 'no_startup': False, 'interface': 'ipython', 'command': None}
101exceptImportError:
102pass103raiseCommandError("Couldn't import {} interface.".format(shell))
/usr/local/lib/python3.6/site-packages/django/core/management/commands/shell.pyinipython(self=<django.core.management.commands.shell.Commandobject>, options={'command': None, 'force_color': False, 'interface': 'ipython', 'no_color': False, 'no_startup': False, 'pythonpath': None, 'settings': None, 'traceback': False, 'verbosity': 1})
21parser.add_argument(
22'--no-startup', action='store_true',
23help='When using plain Python, ignore the PYTHONSTARTUP environment variable and ~/.pythonrc.py script.',
24 )
25parser.add_argument(
26'-i', '--interface', choices=self.shells,
27help='Specify an interactive interpreter interface. Available options: "ipython", "bpython", and "python"',
28 )
29parser.add_argument(
30'-c', '--command',
31help='Instead of opening an interactive shell, run a command as Django and exit.',
32 )
3334defipython(self, options):
35fromIPythonimportstart_ipython--->36start_ipython(argv=[])
start_ipython=<functionstart_ipythonat0x7f34af156158>globalargv=undefined3738defbpython(self, options):
39importbpython40bpython.embed()
4142defpython(self, options):
43importcode4445# Set up a dictionary to serve as the environment for the shell, so46# that tab completion works on objects that are imported at runtime.47imported_objects= {}
48try: # Try activating rlcompleter, because it's handy.49importreadline50exceptImportError:
51pass/usr/local/lib/python3.6/site-packages/IPython/__init__.pyinstart_ipython(argv=[], **kwargs={})
111ThisisapublicAPImethod, andwillsurviveimplementationchanges.
112113Parameters114----------115116argv : listorNone, optional117IfunspecifiedorNone, IPythonwillparsecommand-lineoptionsfromsys.argv.
118Topreventanycommand-lineparsing, passanemptylist: `argv=[]`.
119user_ns : dict, optional120specifythisdictionarytoinitializetheIPythonusernamespacewithparticularvalues.
121kwargs : various, optional122AnyotherkwargswillbepassedtotheApplicationconstructor,
123suchas`config`.
124""125fromIPython.terminal.ipappimportlaunch_new_instance-->126returnlaunch_new_instance(argv=argv, **kwargs)
launch_new_instance=<boundmethodApplication.launch_instanceof<class'IPython.terminal.ipapp.TerminalIPythonApp'>>argv= []
kwargs= {}
127128defstart_kernel(argv=None, **kwargs):
129"""Launch a normal IPython kernel instance (as opposed to embedded) 130 131 `IPython.embed_kernel()` puts a shell in a particular calling scope, 132 such as a function or method for debugging purposes, 133 which is often not desirable. 134 135 `start_kernel()` does full, regular IPython initialization, 136 including loading startup files, configuration, etc. 137 much of which is skipped by `embed()`. 138 139 Parameters 140 ---------- 141 """/usr/local/lib/python3.6/site-packages/traitlets/config/application.pyinlaunch_instance(cls=<class'IPython.terminal.ipapp.TerminalIPythonApp'>, argv=[], **kwargs={})
649lines.append(cls.class_config_section())
650return'\n'.join(lines)
651652defexit(self, exit_status=0):
653self.log.debug("Exiting application: %s"%self.name)
654sys.exit(exit_status)
655656 @classmethod657deflaunch_instance(cls, argv=None, **kwargs):
658"""Launch a global instance of this Application 659 660 If a global instance already exists, this reinitializes and starts it 661 """662app=cls.instance(**kwargs)
663app.initialize(argv)
-->664app.start()
app.start=<boundmethodTerminalIPythonApp.startof<IPython.terminal.ipapp.TerminalIPythonAppobjectat0x7f34aff6e8d0>>665666#-----------------------------------------------------------------------------667# utility functions, for convenience668#-----------------------------------------------------------------------------669670defboolean_flag(name, configurable, set_help='', unset_help=''):
671"""Helper for building basic --trait, --no-trait flags. 672 673 Parameters 674 ---------- 675 676 name : str 677 The name of the flag. 678 configurable : str 679 The 'Class.trait' string of the trait to be set/unset with the flag"""/usr/local/lib/python3.6/site-packages/IPython/terminal/ipapp.pyinstart(self=<IPython.terminal.ipapp.TerminalIPythonAppobject>)
341ifself.log_level<=logging.INFO: print()
342343def_pylab_changed(self, name, old, new):
344"""Replace --pylab='inline' with --pylab='auto'"""345ifnew=='inline':
346warnings.warn("'inline' not available as pylab backend, "347"using 'auto' instead.")
348self.pylab='auto'349350defstart(self):
351ifself.subappisnotNone:
352returnself.subapp.start()
353# perform any prexec steps:354ifself.interact:
355self.log.debug("Starting IPython's mainloop...")
-->356self.shell.mainloop()
self.shell.mainloop=<boundmethodTerminalInteractiveShell.mainloopof<IPython.terminal.interactiveshell.TerminalInteractiveShellobjectat0x7f34af0e95c0>>357else:
358self.log.debug("IPython not interactive...")
359ifnotself.shell.last_execution_succeeded:
360sys.exit(1)
361362defload_default_config(ipython_dir=None):
363"""Load the default config file from the default ipython_dir. 364 365 This is useful for embedded shells. 366 """367ifipython_dirisNone:
368ipython_dir=get_ipython_dir()
369370profile_dir=os.path.join(ipython_dir, 'profile_default')
371app=TerminalIPythonApp()
/usr/local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.pyinmainloop(self=<IPython.terminal.interactiveshell.TerminalInteractiveShellobject>, display_banner=<objectobject>)
548if (notself.confirm_exit) \
549orself.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
550self.ask_exit()
551552else:
553ifcode:
554self.run_cell(code, store_history=True)
555556defmainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
557# An extra layer of protection in case someone mashing Ctrl-C breaks558# out of our internal code.559ifdisplay_bannerisnotDISPLAY_BANNER_DEPRECATED:
560warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
561whileTrue:
562try:
-->563self.interact()
self.interact=<boundmethodTerminalInteractiveShell.interactof<IPython.terminal.interactiveshell.TerminalInteractiveShellobjectat0x7f34af0e95c0>>564break565exceptKeyboardInterruptase:
566print("\n%s escaped interact()\n"%type(e).__name__)
567finally:
568# An interrupt during the eventloop will mess up the569# internal state of the prompt_toolkit library.570# Stopping the eventloop fixes this, see571# https://github.com/ipython/ipython/pull/9867572ifhasattr(self, '_eventloop'):
573self._eventloop.stop()
574575self.restore_term_title()
576577578_inputhook=None/usr/local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.pyininteract(self=<IPython.terminal.interactiveshell.TerminalInteractiveShellobject>, display_banner=<objectobject>)
531defask_exit(self):
532self.keep_running=False533534rl_next_input=None535536definteract(self, display_banner=DISPLAY_BANNER_DEPRECATED):
537538ifdisplay_bannerisnotDISPLAY_BANNER_DEPRECATED:
539warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
540541self.keep_running=True542whileself.keep_running:
543print(self.separate_in, end='')
544545try:
-->546code=self.prompt_for_code()
code='%config Application.verbose_crash=True'self.prompt_for_code=<boundmethodTerminalInteractiveShell.prompt_for_codeof<IPython.terminal.interactiveshell.TerminalInteractiveShellobjectat0x7f34af0e95c0>>547exceptEOFError:
548if (notself.confirm_exit) \
549orself.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
550self.ask_exit()
551552else:
553ifcode:
554self.run_cell(code, store_history=True)
555556defmainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
557# An extra layer of protection in case someone mashing Ctrl-C breaks558# out of our internal code.559ifdisplay_bannerisnotDISPLAY_BANNER_DEPRECATED:
560warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
561whileTrue:
/usr/local/lib/python3.6/site-packages/IPython/terminal/interactiveshell.pyinprompt_for_code(self=<IPython.terminal.interactiveshell.TerminalInteractiveShellobject>)
459# prompt in a different event loop.460# If we don't do this, people could spawn coroutine with a461# while/true inside which will freeze the prompt.462463try:
464old_loop=asyncio.get_event_loop()
465exceptRuntimeError:
466# This happens when the user used `asyncio.run()`.467old_loop=None468469asyncio.set_event_loop(self.pt_loop)
470try:
471withpatch_stdout(raw=True):
472text=self.pt_app.prompt(
473default=default,
-->474**self._extra_prompt_options())
self._extra_prompt_options=<boundmethodTerminalInteractiveShell._extra_prompt_optionsof<IPython.terminal.interactiveshell.TerminalInteractiveShellobjectat0x7f34af0e95c0>>475finally:
476# Restore the original event loop.477asyncio.set_event_loop(old_loop)
478479returntext480481defenable_win_unicode_console(self):
482# Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows483# console by default, so WUC shouldn't be needed.484fromwarningsimportwarn485warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
486DeprecationWarning,
487stacklevel=2)
488489definit_io(self):
/usr/local/lib/python3.6/site-packages/prompt_toolkit/shortcuts/prompt.pyinprompt(self=<prompt_toolkit.shortcuts.prompt.PromptSessionobject>, message=<prompt_toolkit.formatted_text.pygments.PygmentsTokensobject>, editing_mode=None, refresh_interval=None, vi_mode=None, lexer=<IPython.terminal.ptutils.IPythonPTLexerobject>, completer=None, complete_in_thread=False, is_password=None, key_bindings=None, bottom_toolbar=None, style=None, color_depth=None, include_default_pygments_style=None, style_transformation=None, swap_light_and_dark_colors=None, rprompt=None, multiline=True, prompt_continuation=<functionTerminalInteractiveShell._extra_prompt_options.<locals>.<lambda>>, wrap_lines=None, enable_history_search=None, search_ignore_case=None, complete_while_typing=None, validate_while_typing=None, complete_style=<CompleteStyle.MULTI_COLUMN: 'MULTI_COLUMN'>, auto_suggest=None, validator=None, clipboard=None, mouse_support=None, input_processors=[ConditionalProcessor(processor=<prompt_toolkit.l...pt_options.<locals>.<lambda>at0x7f34aee62f28>))], placeholder=None, reserve_space_for_menu=6, enable_system_prompt=None, enable_suspend=None, enable_open_in_editor=None, tempfile_suffix=None, tempfile=None, default='', accept_default=False, pre_run=None, set_exception_handler=True, in_thread=False)
1006self.tempfile=tempfile10071008self._add_pre_run_callables(pre_run, accept_default)
1009self.default_buffer.reset(
1010defaultifisinstance(default, Document) elseDocument(default)
1011 )
1012self.app.refresh_interval=self.refresh_interval# This is not reactive.10131014# If we are using the default output, and have a dumb terminal. Use the1015# dumb prompt.1016ifself._outputisNoneandis_dumb_terminal():
1017withself._dumb_prompt(self.message) asdump_app:
1018returndump_app.run(in_thread=in_thread)
10191020returnself.app.run(
->1021set_exception_handler=set_exception_handler, in_thread=in_threadset_exception_handler=Truein_thread=False1022 )
10231024 @contextmanager1025def_dumb_prompt(self, message: AnyFormattedText="") ->Iterator[Application[_T]]:
1026""" 1027 Create prompt `Application` for prompt function for dumb terminals. 1028 1029 Dumb terminals have minimum rendering capabilities. We can only print 1030 text to the screen. We can't use colors, and we can't do cursor 1031 movements. The Emacs inferior shell is an example of a dumb terminal. 1032 1033 We will show the prompt, and wait for the input. We still handle arrow 1034 keys, and all custom key bindings, but we don't really render the 1035 cursor movements. Instead we only print the typed character that's 1036 right before the cursor."""/usr/local/lib/python3.6/site-packages/prompt_toolkit/application/application.pyinrun(self=<prompt_toolkit.application.application.Applicationobject>, pre_run=None, set_exception_handler=True, in_thread=False)
877# We don't create a new event loop by default, because we want to be878# sure that when this is called multiple times, each call of `run()`879# goes through the same event loop. This way, users can schedule880# background-tasks that keep running across multiple prompts.881try:
882loop=get_event_loop()
883exceptRuntimeError:
884# Possibly we are not running in the main thread, where no event885# loop is set by default. Or somebody called `asyncio.run()`886# before, which closes the existing event loop. We can create a new887# loop.888loop=new_event_loop()
889set_event_loop(loop)
890891returnloop.run_until_complete(
-->892self.run_async(pre_run=pre_run, set_exception_handler=set_exception_handler)
self.run_async=<boundmethodApplication.run_asyncof<prompt_toolkit.application.application.Applicationobjectat0x7f34aef7dac8>>pre_run=Noneset_exception_handler=True893 )
894895def_handle_exception(
896self, loop: AbstractEventLoop, context: Dict[str, Any]
897 ) ->None:
898""" 899 Handler for event loop exceptions. 900 This will print the exception, using run_in_terminal. 901 """902# For Python 2: we have to get traceback at this point, because903# we're still in the 'except:' block of the event loop where the904# traceback is still available. Moving this code in the905# 'print_exception' coroutine will loose the exception.906tb=get_traceback_from_context(context)
907formatted_tb="".join(format_tb(tb))
/usr/local/lib/python3.6/asyncio/base_events.pyinrun_until_complete(self=<_UnixSelectorEventLooprunning=Falseclosed=Falsedebug=False>, future=<Taskfinishedcoro=<Application.run_async() don...TypeError' object has no attribute 'tb_frame'",)>)
473future.add_done_callback(_run_until_complete_cb)
474try:
475self.run_forever()
476except:
477ifnew_taskandfuture.done() andnotfuture.cancelled():
478# The coroutine raised a BaseException. Consume the exception479# to not log a warning, the caller doesn't have access to the480# local task.481future.exception()
482raise483finally:
484future.remove_done_callback(_run_until_complete_cb)
485ifnotfuture.done():
486raiseRuntimeError('Event loop stopped before Future completed.')
487-->488returnfuture.result()
future.result=<built-inmethodresultof_asyncio.Taskobjectat0x7f34aee628c8>489490defstop(self):
491"""Stop running the event loop. 492 493 Every callback already scheduled will still run. This simply informs 494 run_forever to stop looping after a complete iteration. 495 """496self._stopping=True497498defclose(self):
499"""Close the event loop. 500 501 This clears the queues and shuts down the executor, 502 but does not wait for the executor to finish. 503 """/usr/local/lib/python3.6/site-packages/prompt_toolkit/application/application.pyinrun_async(self=<prompt_toolkit.application.application.Applicationobject>, pre_run=None, set_exception_handler=True)
801# happened already in the finally block in `run_async`802# above, but in case of exceptions, that's not always the803# case.804self._is_running=False805806# Also remove the Future again. (This brings the807# application back to its initial state, where it also808# doesn't have a Future.)809self.future=None810811returnresult812finally:
813ifset_exception_handler:
814loop.set_exception_handler(previous_exc_handler)
815-->816returnawait_run_async2()
globalawait=undefined_run_async2=<functionApplication.run_async.<locals>._run_async2at0x7f34aef45a60>817818defrun(
819self,
820pre_run: Optional[Callable[[], None]] =None,
821set_exception_handler: bool=True,
822in_thread: bool=False,
823 ) ->_AppResult:
824""" 825 A blocking 'run' call that waits until the UI is finished. 826 827 This will start the current asyncio event loop. If no loop is set for 828 the current thread, then it will create a new loop. If a new loop was 829 created, this won't close the new loop (if `in_thread=False`). 830 831 :param pre_run: Optional callable, which is called right after the"""/usr/local/lib/python3.6/site-packages/prompt_toolkit/application/application.pyin_run_async2()
783784loop=get_event_loop()
785ifset_exception_handler:
786previous_exc_handler=loop.get_exception_handler()
787loop.set_exception_handler(self._handle_exception)
788789try:
790withset_app(self), self._enable_breakpointhook():
791try:
792result=await_run_async()
793finally:
794# Wait for the background tasks to be done. This needs to795# go in the finally! If `_run_async` raises796# `KeyboardInterrupt`, we still want to wait for the797# background tasks.-->798awaitself.cancel_and_wait_for_background_tasks()
globalawait=undefinedglobalself.cancel_and_wait_for_background_tasks=undefined799800# Set the `_is_running` flag to `False`. Normally this801# happened already in the finally block in `run_async`802# above, but in case of exceptions, that's not always the803# case.804self._is_running=False805806# Also remove the Future again. (This brings the807# application back to its initial state, where it also808# doesn't have a Future.)809self.future=None810811returnresult812finally:
813ifset_exception_handler:
/usr/local/lib/python3.6/site-packages/prompt_toolkit/application/application.pyincancel_and_wait_for_background_tasks(self=<prompt_toolkit.application.application.Applicationobject>)
986987asyncdefcancel_and_wait_for_background_tasks(self) ->None:
988""" 989 Cancel all background tasks, and wait for the cancellation to be done. 990 If any of the background tasks raised an exception, this will also 991 propagate the exception. 992 993 (If we had nurseries like Trio, this would be the `__aexit__` of a 994 nursery.) 995 """996fortaskinself.background_tasks:
997task.cancel()
998999fortaskinself.background_tasks:
1000try:
->1001awaittaskglobalawait=undefinedtask=<Taskfinishedcoro=<Buffer._create_completer_coroutine.<locals>.async_completer() done, definedat/usr/local/lib/python3.6/site-packages/prompt_toolkit/buffer.py:1896>exception=AttributeError("'TypeError' object has no attribute 'tb_frame'",)>1002exceptCancelledError:
1003pass10041005asyncdef_poll_output_size(self) ->None:
1006""" 1007 Coroutine for polling the terminal dimensions. 1008 1009 Useful for situations where `attach_winch_signal_handler` is not sufficient: 1010 - If we are not running in the main thread. 1011 - On Windows. 1012 """1013size: Optional[Size] =None1014interval=self.terminal_size_polling_interval10151016ifintervalisNone:
/usr/local/lib/python3.6/site-packages/prompt_toolkit/buffer.pyinnew_coroutine(*a=(), **kw={'complete_event': CompleteEvent(text_inserted=False, completion_requested=True), 'insert_common_part': True, 'select_first': False, 'select_last': False})
1894running=False18951896 @wraps(coroutine)
1897asyncdefnew_coroutine(*a: Any, **kw: Any) ->Any:
1898nonlocalrunning18991900# Don't start a new function, if the previous is still in progress.1901ifrunning:
1902return19031904running=True19051906try:
1907whileTrue:
1908try:
->1909awaitcoroutine(*a, **kw)
globalawait=undefinedglobalcoroutine=undefineda= ()
kw= {'select_first': False, 'select_last': False, 'insert_common_part': True, 'complete_event': CompleteEvent(text_inserted=False, completion_requested=True)}
1910except_Retry:
1911continue1912else:
1913returnNone1914finally:
1915running=False19161917returncast(_T, new_coroutine)
191819191920class_Retry(Exception):
1921"Retry in `_only_one_at_a_time`."192219231924defindent(buffer: Buffer, from_row: int, to_row: int, count: int=1) ->None:
/usr/local/lib/python3.6/site-packages/prompt_toolkit/buffer.pyinasync_completer(select_first=False, select_last=False, insert_common_part=True, complete_event=CompleteEvent(text_inserted=False, completion_requested=True))
17241725# Don't complete when we already have completions.1726ifself.complete_stateornotself.completer:
1727return17281729# Create an empty CompletionState.1730complete_state=CompletionState(original_document=self.document)
1731self.complete_state=complete_state17321733defproceed() ->bool:
1734"""Keep retrieving completions. Input text has not yet changed 1735 while generating completions."""1736returnself.complete_state==complete_state17371738asyncforcompletioninself.completer.get_completions_async(
->1739document, complete_eventdocument=Document('from dwms.models import My', 26)
complete_event=CompleteEvent(text_inserted=False, completion_requested=True)
1740 ):
1741complete_state.completions.append(completion)
1742self.on_completions_changed.fire()
17431744# If the input text changes, abort.1745ifnotproceed():
1746break17471748completions=complete_state.completions17491750# When there is only one completion, which has nothing to add, ignore it.1751iflen(completions) ==1andcompletion_does_nothing(
1752document, completions[0]
1753 ):
1754delcompletions[:]
/usr/local/lib/python3.6/site-packages/prompt_toolkit/completion/base.pyinget_completions_async(self=DynamicCompleter(<functionPromptSession._create...ils.IPythonPTCompleterobjectat0x7f34fa977160>), document=Document('from dwms.models import My', 26), complete_event=CompleteEvent(text_inserted=False, completion_requested=True))
257def__init__(self, get_completer: Callable[[], Optional[Completer]]) ->None:
258self.get_completer=get_completer259260defget_completions(
261self, document: Document, complete_event: CompleteEvent262 ) ->Iterable[Completion]:
263completer=self.get_completer() orDummyCompleter()
264returncompleter.get_completions(document, complete_event)
265266asyncdefget_completions_async(
267self, document: Document, complete_event: CompleteEvent268 ) ->AsyncGenerator[Completion, None]:
269completer=self.get_completer() orDummyCompleter()
270271asyncforcompletionincompleter.get_completions_async(
-->272document, complete_eventdocument=Document('from dwms.models import My', 26)
complete_event=CompleteEvent(text_inserted=False, completion_requested=True)
273 ):
274yieldcompletion275276def__repr__(self) ->str:
277return"DynamicCompleter(%r -> %r)"% (self.get_completer, self.get_completer())
278279280classConditionalCompleter(Completer):
281""" 282 Wrapper around any other completer that will enable/disable the completions 283 depending on whether the received condition is satisfied. 284 285 :param completer: :class:`.Completer` instance. 286 :param filter: :class:`.Filter` instance. 287 """/usr/local/lib/python3.6/site-packages/prompt_toolkit/completion/base.pyinget_completions_async(self=<IPython.terminal.ptutils.IPythonPTCompleterobject>, document=Document('from dwms.models import My', 26), complete_event=CompleteEvent(text_inserted=False, completion_requested=True))
183 :paramdocument: :class:`~prompt_toolkit.document.Document`instance.
184 :paramcomplete_event: :class:`.CompleteEvent`instance.
185""186whileFalse:
187yield188189asyncdefget_completions_async(
190self, document: Document, complete_event: CompleteEvent191 ) ->AsyncGenerator[Completion, None]:
192""" 193 Asynchronous generator for completions. (Probably, you won't have to 194 override this.) 195 196 Asynchronous generator of :class:`.Completion` objects. 197 """-->198foriteminself.get_completions(document, complete_event):
item=undefinedself.get_completions=<boundmethodIPythonPTCompleter.get_completionsof<IPython.terminal.ptutils.IPythonPTCompleterobjectat0x7f34fa977160>>document=Document('from dwms.models import My', 26)
complete_event=CompleteEvent(text_inserted=False, completion_requested=True)
199yielditem200201202classThreadedCompleter(Completer):
203""" 204 Wrapper that runs the `get_completions` generator in a thread. 205 206 (Use this to prevent the user interface from becoming unresponsive if the 207 generation of completions takes too much time.) 208 209 The completions will be displayed as soon as they are produced. The user 210 can already select a completion, even if not all completions are displayed. 211 """212213def__init__(self, completer: Completer) ->None:
/usr/local/lib/python3.6/site-packages/IPython/terminal/ptutils.pyinget_completions(self=<IPython.terminal.ptutils.IPythonPTCompleterobject>, document=Document('from dwms.models import My', 26), complete_event=CompleteEvent(text_inserted=False, completion_requested=True))
101return102# Some bits of our completion system may print stuff (e.g. if a module103# is imported). This context manager ensures that doesn't interfere with104# the prompt.105106withpatch_stdout(), provisionalcompleter():
107body=document.text108cursor_row=document.cursor_position_row109cursor_col=document.cursor_position_col110cursor_position=document.cursor_position111offset=cursor_to_position(body, cursor_row, cursor_col)
112try:
113yieldfromself._get_completions(body, offset, cursor_position, self.ipy_completer)
114exceptExceptionase:
115fromtracebackimportprint_tb-->116print_tb(e)
print_tb=<functionprint_tbat0x7f34fb309ea0>e=undefined117118 @staticmethod119def_get_completions(body, offset, cursor_position, ipyc):
120""" 121 Private equivalent of get_completions() use only for unit_testing. 122 """123debug=getattr(ipyc, 'debug', False)
124completions=_deduplicate_completions(
125body, ipyc.completions(body, offset))
126forcincompletions:
127ifnotc.text:
128# Guard against completion machinery giving us an empty string.129continue130text=unicodedata.normalize('NFC', c.text)
131# When the first character of the completion has a zero length,/usr/local/lib/python3.6/traceback.pyinprint_tb(tb=TypeError("__init__() got an unexpected keyword argument 'column'",), limit=None, file=None)
38""39returnStackSummary.from_list(extracted_list).format()
4041#42# Printing and Extracting Tracebacks.43#4445defprint_tb(tb, limit=None, file=None):
46"""Print up to 'limit' stack trace entries from the traceback 'tb'. 47 48 If 'limit' is omitted or None, all entries are printed. If 'file' 49 is omitted or None, the output goes to sys.stderr; otherwise 50 'file' should be an open file or file-like object with a write() 51 method. 52 """--->53print_list(extract_tb(tb, limit=limit), file=file)
globalprint_list=<functionprint_listat0x7f34fb3c9620>globalextract_tb=<functionextract_tbat0x7f34fb30d048>tb=TypeError("__init__() got an unexpected keyword argument 'column'",)
limit=Nonefile=None5455defformat_tb(tb, limit=None):
56"""A shorthand for 'format_list(extract_tb(tb, limit))'."""57returnextract_tb(tb, limit=limit).format()
5859defextract_tb(tb, limit=None):
60""" 61 Return a StackSummary object representing a list of 62 pre-processed entries from traceback. 63 64 This is useful for alternate formatting of stack traces. If 65 'limit' is omitted or None, all entries are extracted. A 66 pre-processed stack trace entry is a FrameSummary object 67 containing attributes filename, lineno, name, and line 68 representing the information that is usually printed for a stack"""/usr/local/lib/python3.6/traceback.pyinextract_tb(tb=TypeError("__init__() got an unexpected keyword argument 'column'",), limit=None)
57returnextract_tb(tb, limit=limit).format()
5859defextract_tb(tb, limit=None):
60""" 61 Return a StackSummary object representing a list of 62 pre-processed entries from traceback. 63 64 This is useful for alternate formatting of stack traces. If 65 'limit' is omitted or None, all entries are extracted. A 66 pre-processed stack trace entry is a FrameSummary object 67 containing attributes filename, lineno, name, and line 68 representing the information that is usually printed for a stack 69 trace. The line is a string with leading and trailing 70 whitespace stripped; if the source is not available it is None. 71 """--->72returnStackSummary.extract(walk_tb(tb), limit=limit)
globalStackSummary.extract=<boundmethodStackSummary.extractof<class'traceback.StackSummary'>>globalwalk_tb=<functionwalk_tbat0x7f34fb30dae8>tb=TypeError("__init__() got an unexpected keyword argument 'column'",)
limit=None7374#75# Exception formatting and output.76#7778_cause_message= (
79"\nThe above exception was the direct cause "80"of the following exception:\n\n")
8182_context_message= (
83"\nDuring handling of the above exception, "84"another exception occurred:\n\n")
858687defprint_exception(etype, value, tb, limit=None, file=None, chain=True):
/usr/local/lib/python3.6/traceback.pyinextract(klass=<class'traceback.StackSummary'>, frame_gen=<generatorobjectwalk_tb>, limit=None, lookup_lines=True, capture_locals=False)
330 :paramcapture_locals: IfTrue, thelocalvariablesfromeachframewill331becapturedasobjectrepresentationsintotheFrameSummary.
332""333iflimitisNone:
334limit=getattr(sys, 'tracebacklimit', None)
335iflimitisnotNoneandlimit<0:
336limit=0337iflimitisnotNone:
338iflimit>=0:
339frame_gen=itertools.islice(frame_gen, limit)
340else:
341frame_gen=collections.deque(frame_gen, maxlen=-limit)
342343result=klass()
344fnames=set()
-->345forf, linenoinframe_gen:
f=undefinedlineno=undefinedframe_gen=<generatorobjectwalk_tbat0x7f34aed8d150>346co=f.f_code347filename=co.co_filename348name=co.co_name349350fnames.add(filename)
351linecache.lazycache(filename, f.f_globals)
352# Must defer line lookups until we have called checkcache.353ifcapture_locals:
354f_locals=f.f_locals355else:
356f_locals=None357result.append(FrameSummary(
358filename, lineno, name, lookup_line=False, locals=f_locals))
359forfilenameinfnames:
360linecache.checkcache(filename)
/usr/local/lib/python3.6/traceback.pyinwalk_tb(tb=TypeError("__init__() got an unexpected keyword argument 'column'",))
295""296iffisNone:
297f=sys._getframe().f_back.f_back298whilefisnotNone:
299yieldf, f.f_lineno300f=f.f_back301302303defwalk_tb(tb):
304"""Walk a traceback yielding the frame and line number for each frame. 305 306 This will follow tb.tb_next (and thus is in the opposite order to 307 walk_stack). Usually used with StackSummary.extract. 308 """309whiletbisnotNone:
-->310yieldtb.tb_frame, tb.tb_linenotb.tb_frame=undefinedtb.tb_lineno=undefined311tb=tb.tb_next312313314_RECURSIVE_CUTOFF=3# Also hardcoded in traceback.c.315316classStackSummary(list):
317"""A stack of frames."""318319 @classmethod320defextract(klass, frame_gen, *, limit=None, lookup_lines=True,
321capture_locals=False):
322"""Create a StackSummary from a traceback or stack object. 323 324 :param frame_gen: A generator that yields (frame, lineno) tuples to 325 include in the stack."""AttributeError: 'TypeError'objecthasnoattribute'tb_frame'
Not sure if this is a bug from ipython, but I thought I'd want to let you know in case.
The text was updated successfully, but these errors were encountered:
Most of those have been fixed in more recent version of IPython, though as you are on 3.6 you get the latest 3.6 compatible which is starting to be quite old and does not have those fixes.
IIRC you need to pin jedi to an earlier version (0.13.2 I believe). The stack error is fixed as well, but I don't believe there is a workaround, though if completion does not crash it should not be an issue.
I'm trying to use
ipython
as a stand-in shell for interacting with adjango
server in a docker setup. When entering the shell viadocker-compose exec <container> python manage.py shell -i ipython
I'm being dropped in theipython
shell with thedjango
context available. Everything then works properly, as long as I don't attempt to use tab (auto)completion. It worked just fine with alldjango
instances in containers so far.Specifically, attempting to
Tab
makesipython
not do anything (but stutter for a second), and crashes after manually completing the current command and pressingEnter
.asciinema
recording: https://asciinema.org/a/CoxP5qqiW5dxD7QmPeWX1O6Tq (I attempt to autocomplete after having typedMyTe
) (will vanish after 7 days).On crashing, this cryptic error is being output (extended via the recommended
%config Application.verbose_crash=True
):Not sure if this is a bug from
ipython
, but I thought I'd want to let you know in case.The text was updated successfully, but these errors were encountered: