|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""Utility and helper methods for tmuxp. |
| 3 | +
|
| 4 | +tmuxp.shell |
| 5 | +~~~~~~~~~~~ |
| 6 | +
|
| 7 | +""" |
| 8 | +from __future__ import absolute_import, unicode_literals |
| 9 | + |
| 10 | +import logging |
| 11 | +import os |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +def launch(shell=None, best=True, use_pythonrc=False, **kwargs): |
| 17 | + import code |
| 18 | + |
| 19 | + import libtmux |
| 20 | + |
| 21 | + imported_objects = { |
| 22 | + 'libtmux': libtmux, |
| 23 | + 'Server': libtmux.Server, |
| 24 | + 'Session': libtmux.Session, |
| 25 | + 'Window': libtmux.Window, |
| 26 | + 'Pane': libtmux.Pane, |
| 27 | + 'server': kwargs.get('server'), |
| 28 | + 'session': kwargs.get('session'), |
| 29 | + 'window': kwargs.get('window'), |
| 30 | + 'pane': kwargs.get('pane'), |
| 31 | + } |
| 32 | + |
| 33 | + try: |
| 34 | + # Try activating rlcompleter, because it's handy. |
| 35 | + import readline |
| 36 | + except ImportError: |
| 37 | + pass |
| 38 | + else: |
| 39 | + # We don't have to wrap the following import in a 'try', because |
| 40 | + # we already know 'readline' was imported successfully. |
| 41 | + import rlcompleter |
| 42 | + |
| 43 | + readline.set_completer(rlcompleter.Completer(imported_objects).complete) |
| 44 | + # Enable tab completion on systems using libedit (e.g. macOS). |
| 45 | + # These lines are copied from Lib/site.py on Python 3.4. |
| 46 | + readline_doc = getattr(readline, '__doc__', '') |
| 47 | + if readline_doc is not None and 'libedit' in readline_doc: |
| 48 | + readline.parse_and_bind("bind ^I rl_complete") |
| 49 | + else: |
| 50 | + readline.parse_and_bind("tab:complete") |
| 51 | + |
| 52 | + # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system |
| 53 | + # conventions and get $PYTHONSTARTUP first then .pythonrc.py. |
| 54 | + if use_pythonrc: |
| 55 | + for pythonrc in set( |
| 56 | + [os.environ.get("PYTHONSTARTUP"), os.path.expanduser('~/.pythonrc.py')] |
| 57 | + ): |
| 58 | + if not pythonrc: |
| 59 | + continue |
| 60 | + if not os.path.isfile(pythonrc): |
| 61 | + continue |
| 62 | + with open(pythonrc) as handle: |
| 63 | + pythonrc_code = handle.read() |
| 64 | + # Match the behavior of the cpython shell where an error in |
| 65 | + # PYTHONSTARTUP prints an exception and continues. |
| 66 | + try: |
| 67 | + exec(compile(pythonrc_code, pythonrc, 'exec'), imported_objects) |
| 68 | + except Exception: |
| 69 | + import traceback |
| 70 | + |
| 71 | + traceback.print_exc() |
| 72 | + |
| 73 | + code.interact(local=imported_objects) |
0 commit comments