This question already has an answer here:
- Importing user defined modules in python from a directory 2 answers
I am trying to import a python script containing several defined functions into a different python script using this approach via SO. Since the script I would like to import defines many functions (some of which are nested inside other functions), I would prefer to import the entire script rather than each function individually. I am using a simpler example below.
Say I have a folder on my desktop
named 'workspace'
. In the folder 'workspace'
, there is a script named 'pre.py'
that contains a single function (defined below) and a blank file named '__init__.py'
.
def get_g(x):
""" Sample Function """
if isinstance(x, list):
res = [xi**2 for xi in x]
else:
res = x**2
return res
In the same 'workspace'
folder, there is a script named 'post.py'
, in which I would like to import all functions defined in 'pre.py'
. A sample script of 'post.py'
is below.
ATTEMPT #1:
import matplotlib.pyplot as plt
def get_my_imports(script_name, fileloc="/Users/myname/Desktop/workspace"):
""" Import Sample Function (defined above) """
from fileloc import script_name
get_my_imports('pre.py')
x = np.linspace(1, 10, 100)
y = get_g(x)
plt.plot(x, y)
plt.show()
>> ImportError: No module named 'fileloc'
ATTEMPT #2:
import matplotlib.pyplot as plt
from "/Users/myname/Desktop/workspace" import 'tst.py' ## error in this line
x = np.linspace(1, 10, 100)
y = get_g(x)
plt.plot(x, y)
plt.show()
>> SyntaxError: invalid syntax
In my first attempt, I tried to generalize the approach of importing py scripts. But the interpreter thinks fileloc
is an importable module rather than my intention. My second attempt tells me that I am not understanding something fundamental about how to do this. How can this style of approach be adapted to work correctly? (I am using an apple laptop if it's relevant to the file location.)