pythontyper

Tokensize a string in python


This is what I'm trying to do:

from typer import Option, Typer, echo
app = Typer(name="testapp")
@app.command("run", help="Run a command in my special environment")
def run(
    command: str,
) -> None:
    print (command)

When running this testapp using

testapp run "foobar --with baz --exclude bar --myfancyotheroption"

It works perfectly well because it accepts "command" as a string, instead I wish to be able to tokenize it and just run it as

testapp run foobar --with baz --exclude bar --myfancyotheroption

In the current content, I might have anything as a part of the command, so how do I approach this?


Solution

  • You can use Context :

    from typer import Typer, Context
    
    app = Typer(name="testapp")
    
    @app.command(
            "run",
            context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
            help="Run a command in my special environment"
    )
    def run(ctx: Context) -> None:
        command = " ".join(ctx.args)
        print(command)