3

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'

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?

5
  • it because IDE generated __pycache__ and in Linux also like that Feb 26, 2020 at 10:52
  • @ArtyomVancyan is there any workaround? I mean I cannot put everything in one big file
    – Anna
    Feb 26, 2020 at 10:54
  • 1
    MODULE_PATH should be a path to a directory, not a __init__.py (or any other) file.
    – martineau
    Feb 26, 2020 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, 2020 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, 2020 at 11:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.