Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix typer command cannot run scripts that imports other scripts #869

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions tests/assets/cli/import_other.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from imported_by_other import hello
from subdir.imported_nested import echo


def main(name: str):
hello(name)
echo(name)
2 changes: 2 additions & 0 deletions tests/assets/cli/imported_by_other.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def hello(name):
print(f"Hello {name}")
2 changes: 2 additions & 0 deletions tests/assets/cli/subdir/imported_nested.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def echo(arg):
print(f"echo: {arg}")
22 changes: 22 additions & 0 deletions tests/test_cli/test_import_other.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import subprocess
import sys


def test_script():
result = subprocess.run(
[
sys.executable,
"-m",
"coverage",
"run",
"-m",
"typer",
"tests/assets/cli/import_other.py",
"run",
"Dr. Magic",
],
capture_output=True,
encoding="utf-8",
)
assert "Hello Dr. Magic" in result.stdout
assert "echo: Dr. Magic" in result.stdout
2 changes: 2 additions & 0 deletions typer/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ def get_typer_from_state() -> Optional[typer.Typer]:
if state.file:
module_name = state.file.name
spec = importlib.util.spec_from_file_location(module_name, str(state.file))
# the module may import other modules in the same directory
sys.path.append(str(state.file.parent))
elif state.module:
spec = importlib.util.find_spec(state.module)
if spec is None:
Expand Down
Loading