How to have a python input that behaves like bash input?

I want to get user input in a python script after the script has begun, not as a command line argument.

I tried using pythons input method, but this behaves like a standard text-box. Is there an input type in python that behaves like the bash terminal with predictive suggestions and bash syntax such as file{1..7}

1 answer

  • answered 2018-11-08 07:46 AracKnight

    It would be helpful if you'd add which operating system you are using and for what purpose you want the 'bash-like' input. The most common way I guess would be to implement a CLI yourself and then calling the bash, but this may be a bit over the top depending on what you want to achieve.

    For implementing a CLI I suggest to have a look at the click-package. Just a quick example:

    import click
    import click_repl
    from subprocess import Popen, DEVNULL
    import os
    from prompt_toolkit.history import FileHistory
    
    @click.group(invoke_without_command=True)
    @click.pass_context
    def cli(ctx):
        if ctx.invoked_subcommand is None:
            ctx.invoke(repl)
    
    @cli.command()
    @click.option("--directory", "-d", prompt=True, help="Directory to cd into")
    def cd(directory):
        command = "cd {0}".format(directory)
        Popen(command, shell=True, stdin=None, stdout=DEVNULL, stderr=None)
    
    @cli.command()
    def repl():
    prompt_kwargs = {
        'history': FileHistory(os.path.expanduser('~/.repl_history'))
    }
    click_repl.repl(click.get_current_context(), prompt_kwargs)
    
    try:
        cli(obj={})
    except SystemExit:
        pass
    

    It is important to catch a SystemExit because click always throw one after executing a command. And you have to implement every bash command you want to allow as a click command.