Last active
November 26, 2022 11:47
-
-
Save thibaud-opal/84eceafd67bf67361f5b194aafdd75bc to your computer and use it in GitHub Desktop.
Using typer with classes as commands
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from my_commands import PrintCommand | |
from my_lib import PrinterDriver | |
import os | |
import typer | |
app = typer.Typer() | |
myPrinter = PrinterDriver() | |
commands = { | |
"print": PrintCommand(myPrinter) | |
} | |
for name, command in commands.items(): | |
app.add_typer(command.load_commands(), name=name) | |
if __name__ == '__main__': | |
app() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from my_lib import PrinterDriver | |
import typer | |
app = typer.Typer() | |
class PrintCommand(): | |
def __init__(self, printer: PrinterDriver): | |
self.__printer = printer | |
def load_commands(self): | |
@app.command() | |
def message(message_body: str): | |
self.__printer.print(message_body) | |
@app.command() | |
def check_ink_levels(): | |
if self.__printer.out_of_ink(): | |
typer.echo("Renew cartridges) | |
else | |
typer.echo("Levels OK") | |
return app |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PrinterDriver(): | |
def print(self, text: str): | |
typer.echo(text) | |
def out_of_ink(self) | |
return self.__inkLevels > 0.1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment