2

I have to import custom functions from script A to script B and execute them in script B.

Now it looks like this:

Script_B.py

import os
import sys
from A import function_aa
from A import function_ab
from A import function_ac


def main():
    function_aa()
    function_ab()
    function_ac()

if __name__ == "__main__":
    main()


If I run it in the IDE it is ok, but Windows Task Scheduler doesn't recognize these custom functions and throws an error ModuleNotFoundError: No module named 'A'

Ok I tried to include a path to A like this:

import importlib
import sys

MODULE_PATH = 'C://foo//bar//__init__.py' # A.py is in bar folder and contains A.py and __init__.py
MODULE_NAME = "A"
spec = importlib.util.spec_from_file_location(MODULE_NAME, MODULE_PATH)
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)

Then I have this error ImportError: cannot import name 'function_aa' from 'A'

Is there any workaround this Task Scheduler problem with importing your own function?

deadshot
  • 8,881
  • 4
  • 20
  • 39
Anna
  • 914
  • 9
  • 25
  • it because IDE generated `__pycache__` and in Linux also like that – Artyom Vancyan Feb 26 '20 at 10:52
  • @ArtyomVancyan is there any workaround? I mean I cannot put everything in one big file – Anna Feb 26 '20 at 10:54
  • 1
    `MODULE_PATH` should be a path to a _directory_, not a `__init__.py` (or any other) file. – martineau Feb 26 '20 at 11:17
  • @martineau it worked thanks! Is is possible to import not one but several custom modules from different files or directories? – Anna Feb 26 '20 at 11:54
  • 1
    Anna: Sure. Just make the code you're using new into a function that's passed one or more augments that tell it what module to import (like its name and path) and use those in the function's code instead of the hardcoded values in it now. Once that is done you can call it multiple time for different modules. – martineau Feb 26 '20 at 11:59

0 Answers0