[英]Not able to import Python module
I am having a server and a testing module in falcon but I am not able to import the server module into the testing module when running the test cases. 我在falcon中有一个服务器和一个测试模块但是在运行测试用例时我无法将服务器模块导入测试模块。
This is my hierarchy: 这是我的层次结构:
project
|
--__init__.py
--server.py
|
/tests
|
--__init__.py
-- apitest.py
This is my testing code 这是我的测试代码
"""
Unit test for Ping api resource
"""
from falcon import testing
import pytest
import server
@pytest.fixture(scope='module')
def client():
return testing.TestClient(server.api)
def test_get_message(client):
result = client.simulate_get('/api/ping')
assert result.status_code == 200
But when i run it it shows: 但是,当我运行它时,它显示:
Traceback:
apiTest.py:7: in <module>
import server
E ImportError: No module named 'server'
What am I doing wrong here. 我在这做错了什么。
Python checks for the module only in the current path of the script, which in your case is /tests
. Python仅在脚本的当前路径中检查模块,在您的情况下是
/tests
。 You would need to add /project
to your path as well. 您还需要添加
/project
到您的路径。 The following code snippet should work: 以下代码段应该有效:
import sys
sys.path.append("../")
import server
First you have to set the add your project directory to the PYTHONPATH or put your project inside a directory that is already added. 首先,您必须将项目目录添加到PYTHONPATH,或将项目放在已添加的目录中。 This lets python to use your package.
这让python可以使用你的包。
You can add the directory using set
command on cmd
. 您可以在
cmd
上使用set
命令添加目录。 For example if you want to add C:\\Python
use command set PYTHONPATH = C:\\Python
例如,如果要添加
C:\\Python
使用命令set PYTHONPATH = C:\\Python
Now to import server.py
you have to type import project.server
or from project import server
. 现在要导入
server.py
您必须输入import project.server
或from project import server
。
If you type import project.server
, to use a function in server you will have to type in project.server.<fuction>()
and if you used from project import server
you will have to use server.<function>()
. 如果键入
import project.server
,要在服务器中使用函数,则必须输入project.server.<fuction>()
,如果from project import server
使用from project import server
则必须使用server.<function>()
。
The best solution would be to make your package installable, rather then fiddle with the PYTHONPATH. 最好的解决方案是让你的包可以安装,而不是摆弄PYTHONPATH。 See guidelines to python packaging here: https://packaging.python.org/tutorials/packaging-projects/
请参阅python包装指南: https : //packaging.python.org/tutorials/packaging-projects/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.