This commit is contained in:
Will McGugan
2022-05-24 09:54:42 +01:00
parent e6a9a37f80
commit 7fd9aa27b5

View File

@@ -1,6 +1,6 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from typing import cast, TYPE_CHECKING
from importlib_metadata import version
@@ -28,6 +28,18 @@ class AppFail(Exception):
def import_app(import_name: str) -> App:
"""Import an app from it's import name.
Args:
import_name (str): A name to import, such as `foo.bar`
Raises:
AppFail: If the app could not be found for any reason.
Returns:
App: A Textual application
"""
import inspect
import importlib
import sys
@@ -39,10 +51,26 @@ def import_app(import_name: str) -> App:
lib, _colon, name = import_name.partition(":")
name = name or "app"
if lib.endswith(".py"):
# We're assuming the user wants to load a .py file
try:
with open(lib) as python_file:
py_code = python_file.read()
except Exception as error:
raise AppFail(str(error))
global_vars: dict[str, object] = {}
exec(py_code, global_vars)
try:
app = global_vars[name]
except KeyError:
raise AppFail(f"App {name!r} not found in {lib!r}")
else:
# Assuming the user wants to import the file
try:
module = importlib.import_module(lib)
except ImportError as error:
raise
raise AppFail(str(error))
try:
@@ -53,14 +81,30 @@ def import_app(import_name: str) -> App:
if inspect.isclass(app) and issubclass(app, App):
app = App()
return app
return cast(App, app)
@run.command("run")
@click.argument("import_name", metavar="IMPORT")
@click.argument("import_name", metavar="FILE or FILE:APP")
@click.option("--dev", "dev", help="Enable development mode", is_flag=True)
def run_app(import_name: str, dev: bool) -> None:
"""Run a Textual app."""
"""Run a Textual app.
The code to run may be given as a path (ending with .py) or as a Python
import, which will load the code and run an app called "app". You may optionally
add a colon plus the class or class instance you want to run.
Here are some examples:
textual run foo.py
textual run foo.py:MyApp
textual run module.foo
textual run module.foo:MyApp
"""
import os
import sys