-2

I need to write a function that imports a python script by absolute path. For example

my_path = "/my/path/to/python/script.py"

def import_script_by_absolute_path(path):
    ???

my_script = import_script_by_absolute_path(my_path)
print(my_script.my_sum(2, 2))
# prints 4

/my/path/to/python/script.py contains:

def my_sum(a, b):
    return a + b

UPD: Alternatively, you can suggest a function from a library that does it

UPD2: The question you lead to doesn't solve my problem. I need a function exactly and I can't understand how to do a function from the answers to this question

1 Answers1

1

you need to add it to sys's path variable:

import sys
sys.path.append('/foo/bar/my_module')
import my_module
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Farid Fakhry
  • 354
  • 1
  • 10