Python 导入自定义函数

Python 导入自定义函数,python,Python,设置 我在两个不同的位置有2个.py文件,即'mypath/folder\u A'和'mypath/folder\u B' 文件A.py包含两个需要导入B.py的自定义函数 A.py看起来像 def test_function_1(x): y = x + 1 return y def test_function_2(x): y = x + 2 return y os.chdir('/mypath/folder_A') import A test_functi

设置

我在两个不同的位置有2个
.py
文件,即
'mypath/folder\u A'
'mypath/folder\u B'

文件
A.py
包含两个需要导入
B.py
的自定义函数

A.py
看起来像

def test_function_1(x):
    y = x + 1
    return y

def test_function_2(x):
    y = x + 2
    return y
os.chdir('/mypath/folder_A')
import A

test_function_1(1)
test_function_2(1)
而且
B.py
看起来像

def test_function_1(x):
    y = x + 1
    return y

def test_function_2(x):
    y = x + 2
    return y
os.chdir('/mypath/folder_A')
import A

test_function_1(1)
test_function_2(1)

问题

当我运行
B.py
时,我得到
name错误:name'test\u function\u 1'未定义

但是如果我将
B.py
调整为

from A import test_function_1, test_function_2
然后运行
B.py
,它就可以工作了


问题

如何将函数从
A.py
导入
B.py
而不必全部命名


也就是说,是否有来自导入所有内容的

您正在查找的内容:

from A import *
您还可以执行以下操作:

import A

A.test_function_1(1)
或:

此外,LIB通常从
$PYTHONPATH

因此,如果您在
.bashrc
中编写这一行:

export PYTHONPATH="$PYTHONPATH:/mypath/folder_A/"
要在GNU/Linux上编辑
.bashrc

gedit $HOME/.bashrc
这样就不需要您的
os.chdir()
,您可以从任何地方直接导入

您的
B.py
将如下所示:

from A import *

test_function_1(1)
test_function_2(1)

您要找的是:

from A import *
您还可以执行以下操作:

import A

A.test_function_1(1)
或:

此外,LIB通常从
$PYTHONPATH

因此,如果您在
.bashrc
中编写这一行:

export PYTHONPATH="$PYTHONPATH:/mypath/folder_A/"
要在GNU/Linux上编辑
.bashrc

gedit $HOME/.bashrc
这样就不需要您的
os.chdir()
,您可以从任何地方直接导入

您的
B.py
将如下所示:

from A import *

test_function_1(1)
test_function_2(1)

非常感谢!我还没有达到bash脚本的级别。仍在从IDE运行我的脚本。一旦可以,我会接受答案。如果你在linux上,请参阅我的编辑:)非常感谢!我还没有达到bash脚本的级别。仍在从IDE运行我的脚本。一旦可以,我将接受答案。如果您在linux上,请参阅我的编辑:)