summaryrefslogtreecommitdiff
path: root/dotfiles/programming/python/startup_script.py
blob: 403afe58d2fd08353cced04a5d93077f939d7422 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import sys as sys_

# Adapted from /usr/lib/python3.7/site.py # enablerlcompleter
def register_readline():
    import os
    import atexit
    try:
        import readline
        import rlcompleter
    except ImportError:
        return

    # Reading the initialization (config) file may not be enough to set a
    # completion key, so we set one first and then read the file.
    readline_doc = getattr(readline, '__doc__', '')
    if readline_doc is not None and 'libedit' in readline_doc:
        readline.parse_and_bind('bind ^I rl_complete')
    else:
        readline.parse_and_bind('tab: complete')

    try:
        readline.read_init_file()
    except OSError:
        # An OSError here could have many causes, but the most likely one
        # is that there's no .inputrc file (or .editrc file in the case of
        # Mac OS X + libedit) in the expected location.  In that case, we
        # want to ignore the exception.
        pass

    if readline.get_current_history_length() == 0:
        # If no history was loaded, default to .python_history.
        # The guard is necessary to avoid doubling history size at
        # each interpreter exit when readline was already configured
        # through a PYTHONSTARTUP hook, see:
        # http://bugs.python.org/issue5845#msg198636
        environ = os.environ.get("XDG_STATE_HOME") or os.environ.get("XDG_DATA_HOME")
        if environ is not None:
            if not os.path.exists(os.path.join(environ, "python")):
                os.mkdir(os.path.join(environ, "python"))
            history = os.path.join(environ, "python", "history")
        else:
            history = os.path.join(os.path.expanduser('~'),
                                   '.python_history')
        try:
            readline.read_history_file(history)
        except OSError:
            pass
        atexit.register(readline.write_history_file, history)

sys_.__interactivehook__ = register_readline

del sys_