[英]python 3.6 unable to resolve import if module is executed from another folder
I have folder and code structure like this 我有这样的文件夹和代码结构
root folder
|
|---core folder
| |
| |----transaction.py
| |
| |----executetransaction.py
|
|---test folder
|
|----test_execute_transaction.py
transaction.py transaction.py
class Transaction:
def __init__(self,json):
print("in create object")
executetransaction.py executetransaction.py
from transaction import Transaction
def execute_transaction(json):
trsobj = Transaction(json)
test_execute_transaction.py test_execute_transaction.py
import sys
sys.path.append("../")
from core import executetransaction
executetransaction.execute_transaction({"a":"b"})
when I execute test_execute_transaction
, it is able to import executetransaction
from core folder but I get ModuleNotFoundError: No module named 'transaction'
on the import code line in executetransaction
module. 当我执行test_execute_transaction
,它能够从核心文件夹中import executetransaction
,但是我得到ModuleNotFoundError: No module named 'transaction'
executetransaction
模块中的导入代码行上ModuleNotFoundError: No module named 'transaction'
的模块。
If I run execute_transaction({"a":"b"})
in executetransaction
module then transaction
is imported as expected and I get "in create object"
. 如果我在executetransaction
模块中运行execute_transaction({"a":"b"})
,那么transaction
将按预期方式导入,并且我得到"in create object"
。
I have added empty __init__.py
in all folders. 我在所有文件夹中都添加了空的__init__.py
。
This is my first time posting question here, please tell me if more details are required. 这是我第一次在这里发布问题,请告诉我是否需要更多详细信息。
This may help you Using local imports 这可以帮助您使用本地导入
When importing the package, Python searches through the directories on sys.path looking for the package subdirectory. 导入软件包时,Python在sys.path上的目录中搜索以寻找软件包的子目录。 docs.python.org/3/tutorial/modules docs.python.org/3/tutorial/modules
Ok your problem is how you import the transaction module in executetransaction.py. 好的,您的问题是如何在executetransaction.py中导入事务模块。
Change from transaction import Transaction
to from .transaction import Transaction
. from transaction import Transaction
更改为from .transaction import Transaction
。 The dot operator tells python that you're wanting to import from the current package. 点运算符告诉python您要从当前包中导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.