问题
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.)
回答1:
Since your two python files are in the same workspace folder, you can simply write
import pre
in post.py. After importing a module named pre, you can use a function func defined in it by
pre.func()
If you don't want to type the name of the module for a given function func each time you use it, you can do
from pre import func
func()
You can also import a given module and give it an alias for convenience. For example,
import pre as p
p.func()
Edit: Add module and function usages.
来源:https://stackoverflow.com/questions/46996982/how-to-import-all-defined-functions-from-python-script-one-into-python-script-tw