1
1
import asyncio
2
+ import os
2
3
import signal
4
+ import sys
5
+ from contextlib import contextmanager
3
6
from importlib import import_module
4
7
from logging import basicConfig , getLevelName , getLogger
5
8
from multiprocessing import Process
6
9
from pathlib import Path
7
10
from time import sleep
8
- from typing import Any , List
11
+ from typing import Any , Generator , List
9
12
10
13
from taskiq .abc .broker import AsyncBroker
11
14
from taskiq .cli .args import TaskiqArgs
@@ -39,6 +42,32 @@ def signal_handler(_signal: int, _frame: Any) -> None:
39
42
process .join ()
40
43
41
44
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
+
42
71
def import_broker (broker_spec : str ) -> Any :
43
72
"""
44
73
It parses broker spec and imports it.
@@ -50,7 +79,8 @@ def import_broker(broker_spec: str) -> Any:
50
79
import_spec = broker_spec .split (":" )
51
80
if len (import_spec ) != 2 :
52
81
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 ])
54
84
return getattr (module , import_spec [1 ])
55
85
56
86
@@ -63,7 +93,8 @@ def import_from_modules(modules: list[str]) -> None:
63
93
for module in modules :
64
94
try :
65
95
logger .info (f"Importing tasks from module { module } " )
66
- import_module (module )
96
+ with add_cwd_in_path ():
97
+ import_module (module )
67
98
except ImportError :
68
99
logger .warning (f"Cannot import { module } " )
69
100
0 commit comments