[Python] How can I add a command to the Python interactive shell?

Discussão em 'Python' iniciado por Stack, Janeiro 31, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to save myself just a few keystrokes for a command I type fairly regularly in Python.

    In my python startup script, I define a function called load which is similar to import, but adds some functionality. It takes a single string:

    def load(s):
    # Do some stuff
    return something


    In order to call this function I have to type

    >>> load('something')


    I would rather be able to simply type:

    >>> load something


    I am running Python with readline support, so I know there exists some programmability there, but I don't know if this sort of thing is possible using it.

    I attempted to get around this by using the InteractivConsole and creating an instance of it in my startup file, like so:

    import code, re, traceback

    class LoadingInteractiveConsole(code.InteractiveConsole):
    def raw_input(self, prompt = ""):
    s = raw_input(prompt)
    match = re.match('^load\s+(.+)', s)
    if match:
    module = match.group(1)
    try:
    load(module)
    print "Loaded " + module
    except ImportError:
    traceback.print_exc()
    return ''
    else:
    return s

    console = LoadingInteractiveConsole()
    console.interact("")


    This works with the caveat that I have to hit Ctrl-D twice to exit the python interpreter: once to get out of my custom console, once to get out of the real one.

    Is there a way to do this without writing a custom C program and embedding the interpreter into it?

    Edit


    Out of channel, I had the suggestion of appending this to the end of my startup file:

    import sys
    sys.exit()


    It works well enough, but I'm still interested in alternative solutions.

    Continue reading...

Compartilhe esta Página