导入自定义函数
设置
我有2个.py在2个不同地点,即文件'mypath/folder_A'和'mypath/folder_B'。
文件A.py包含 2 个需要导入到B.py.
A.py 好像,
def test_function_1(x):
y = x + 1
return y
def test_function_2(x):
y = x + 2
return y
和B.py模样,
os.chdir('/mypath/folder_A')
import A
test_function_1(1)
test_function_2(1)
问题
当我跑步时B.py,我得到了NameError: name 'test_function_1' is not defined。
但如果我适应B.py了,
from A import test_function_1, test_function_2
并运行B.py,它的工作原理。
题
如何将函数从A.pyinto 导入B.py而不必全部命名?
即有from A import everything吗?
回答
你在找什么:
from A import *
你也可以这样做:
import A
A.test_function_1(1)
或者:
import A as a
a.test_function_1(1)
此外,库通常从 $PYTHONPATH
所以如果你在你的.bashrc:
export PYTHONPATH="$PYTHONPATH:/mypath/folder_A/"
.bashrc在 GNU/Linux 上编辑:
gedit $HOME/.bashrc
然后就不需要你的了os.chdir(),你可以直接从任何地方导入。
你B.py会看起来像:
from A import *
test_function_1(1)
test_function_2(1)