简体   繁体   English

在运行时将 package 目录显式添加到 sys.path 后找不到模块

[英]Module not found after explicitly adding package dir to sys.path at runtime

Python cannot find 'mypackage' in this scenario: Python 在这种情况下找不到“mypackage”:

Tree:树:

- myproject
    - mypackage
        - __init__.py
        - mymodule.py
    - tests
        - test.py

Contents of test.py test.py的内容

import sys
from pathlib import Path

p = Path('.')
sys.path.append(p.absolute())

import mypackage                 # ModuleNotFoundError
from mypackage import mymodule   # ModuleNotFoundError

I also printed all the entries from sys.path, where myproject is included.我还打印了包含myproject的 sys.path 中的所有条目。

What am I missing here?我在这里想念什么?

EDIT:编辑:

I am running python from the myproject folder, so the '.'我正在从myproject文件夹运行 python,所以“。” technically works, but I take the point that it's probably not how you should do it.从技术上讲是可行的,但我认为这可能不是您应该这样做的方式。 The problem however, seems to have been sys.path not handling a Path object?然而,问题似乎是 sys.path 没有处理路径 object? The solution was string conversion in this case.在这种情况下,解决方案是字符串转换。

The dot in p = Path('.') just refers to whatever is the current working directory. p = Path('.')中的点仅指当前工作目录。 It may not be the right directory to allow importing mypackage .它可能不是允许导入mypackage的正确目录。

To inject the correct location it could be p = Path(__file__).parent.parent instead.要注入正确的位置,它可能是p = Path(__file__).parent.parent But the correct solution here is actually not to append in sys.path at all, it's to install your package in development mode for running the tests.但是这里正确的解决方案实际上根本不是sys.path的 append ,而是在开发模式下安装 package以运行测试。 This links your code into site-packages dir, which is already on sys.path , in the more usual way.这会以更常用的方式将您的代码链接到已经在sys.path上的 site-packages 目录。

You are not correctly referencing the file, because '.'您没有正确引用该文件,因为 '.' means the current working directory, use this instead:表示当前工作目录,请改用:

p = str(Path(Path(__file__).parent.absolute()).parent.absolute())
sys.path.insert(0, p)

A possible solution:一个可能的解决方案:

in __init__.py__init__.py

from .mymodule import *

Ensure myproject folder absolute path is in the PYTHONPATH environment variable eg in unix/linux:确保 myproject 文件夹的绝对路径位于PYTHONPATH环境变量中,例如在 unix/linux 中:

export PYTHONPATH=path_to_my_project

or in windows: you can create a batch like this one (place in myproject)或在 windows 中:您可以像这样创建一批(放在 myproject 中)

@ echo off
echo setting PYTHONPATH to %~dp0
setx PYTHONPATH %~dp0
pause

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM