python-3.xcommand-linetyper

How to determine if Python script was run using typer?


I want to change the behaviour of a function based on whether it was normally called or called via typer command line program...

from typer import Typer

app = typer.Typer()

@app.command()
def do(a, b, c):
   output = a+b+c
   if <invoked via typer app>:
      print(output)
   return output

if __name__ == '__main__':
   app()

What would the right thing be in place of <invoiked via typer app> above?

Via app.callback()

It can be solved by setting a global or environment variable but it feels like a hack


Solution

  • I'm not the biggest fan of this solution myself as it also kind of pollutes the function signature, however you can achieve it by adding the Context like so:

    from typer import Typer, Context
    
    app = Typer()
    
    
    @app.command()
    def do(
        a,
        b,
        c,
        ctx: Context = None,  # type: ignore
    ):
        output = a + b + c
        if ctx:
            print(output)
        return output
    
    
    if __name__ == "__main__":
        app()
    

    Read more about its intended uses here https://typer.tiangolo.com/tutorial/commands/context/