我有一个简单的 python 项目,其目录结构如下:
sample-project/
main/
config/
config.yaml
docker/
Dockerfile
tests/
__init__.py
sometests.py
config.py
run.py
__init__.py
requirements.txt
README.rst
在config.py文件中,我有:
import yaml
class Config:
def __init__(self):
with open("config/config.yaml", 'r') as ymlfile:
cfg = yaml.load(ymlfile)
self.host = cfg["mysql"]["host"]
self.database = cfg["mysql"]["database"]
self.user = cfg["mysql"]["user"]
self.password = cfg["mysql"]["password"]
my_config = Config()
在run.py文件中,我有一个导入语句,如下所示:
from main.config import my_config
当我使用命令行运行时:python3.5 run.py,我收到错误:
from main.config import my_config
ImportError: No module named 'main'
但是当我在 run.py 导入中添加它时,它可以工作:
import sys
sys.path.append('/home/tomas/sample-project/')
有没有比给出绝对路径或任何其他方式更好的方法来使其工作?请举一些例子:)
最佳答案
一般来说,永远不要在程序中触摸sys.path
。
由于 main/
(不是最好的名称)包含 __init__.py
,我们将其视为一个包,所以让我们 make it runnable as one 。这样导入就会被正确考虑。
添加main/__main__.py
,例如
from main.run import run
if __name__ == "__main__":
run()
然后运行您的应用程序
python -m main
而不是
python main/main.py
关于python - 有没有更好的方法在 python 项目中设置 sys.path.append ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59562426/