设置
我有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.py
into 导入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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句