11import asyncio
2+ import os
23import signal
4+ import sys
5+ from contextlib import contextmanager
36from importlib import import_module
47from logging import basicConfig , getLevelName , getLogger
58from multiprocessing import Process
69from pathlib import Path
710from time import sleep
8- from typing import Any , List
11+ from typing import Any , Generator , List
912
1013from taskiq .abc .broker import AsyncBroker
1114from taskiq .cli .args import TaskiqArgs
@@ -39,6 +42,32 @@ def signal_handler(_signal: int, _frame: Any) -> None:
3942 process .join ()
4043
4144
45+ @contextmanager
46+ def add_cwd_in_path () -> Generator [None , None , None ]:
47+ """
48+ Adds current directory in python path.
49+
50+ This context manager adds current directory in sys.path,
51+ so all python files are discoverable now, without installing
52+ current project.
53+
54+ :yield: none
55+ """
56+ cwd = os .getcwd ()
57+ if cwd in sys .path :
58+ yield
59+ else :
60+ logger .debug (f"Inserting { cwd } in sys.path" )
61+ sys .path .insert (0 , cwd )
62+ try :
63+ yield
64+ finally :
65+ try : # noqa: WPS505
66+ sys .path .remove (cwd )
67+ except ValueError :
68+ logger .warning (f"Cannot remove '{ cwd } ' from sys.path" )
69+
70+
4271def import_broker (broker_spec : str ) -> Any :
4372 """
4473 It parses broker spec and imports it.
@@ -50,7 +79,8 @@ def import_broker(broker_spec: str) -> Any:
5079 import_spec = broker_spec .split (":" )
5180 if len (import_spec ) != 2 :
5281 raise ValueError ("You should provide broker in `module:variable` format." )
53- module = import_module (import_spec [0 ])
82+ with add_cwd_in_path ():
83+ module = import_module (import_spec [0 ])
5484 return getattr (module , import_spec [1 ])
5585
5686
@@ -63,7 +93,8 @@ def import_from_modules(modules: list[str]) -> None:
6393 for module in modules :
6494 try :
6595 logger .info (f"Importing tasks from module { module } " )
66- import_module (module )
96+ with add_cwd_in_path ():
97+ import_module (module )
6798 except ImportError :
6899 logger .warning (f"Cannot import { module } " )
69100
0 commit comments