Typer command in a python wrapper script #754
First Check
Commit to Help
Example Codeimport sys
from my_typer_app.main import app
sys.stdout = open("batch_file_log", mode="at", encoding="ascii", buffering=1)
sys.stderr = open("batch_file_log", mode="at", encoding="ascii", buffering=1)
app()
print("This line is never executed")DescriptionHello, I have build a CLI with Typer that do some tasks. I have to schedule task execution (with cron for exemple) but for scheduled task, i want to redirect all output (stdin & stderr) to logfile. SO, i have created a python script that import my Typer app "app" and launch it after stdin/stderr redirection Now, i must retrieve "app" return code to send an alert if this is not 0. How could i do that ? Thanks Operating SystemLinux Operating System DetailsNo response Typer Version0.9.0 Python VersionPython 3.8.16 Additional ContextNo response |
Replies: 1 comment 1 reply
|
Your script exits before getting to the last print because the You could try to catch the exception and access the exit code like this: try:
app()
except SystemExit as e:
print(f"Exited with exit code {e.code}")But a better approach might be to use the |
Your script exits before getting to the last print because the
app()invocation raises aSystemExitexception, since it is expecting to be the last thing run in the process.You could try to catch the exception and access the exit code like this:
But a better approach might be to use the
CliRunnerutility fromtyper.testing, which is designed to do basically what you are trying to do: run a typer app from the context of a longer-running piece of code. It can also capture the output for you, which might be cleaner than patchingstderrandstdout.You can read more about
CliRunnerhere and here