开发者

How can I load the parent directory of a script as a module, without adding all of the siblings of that directory's parent directory to my sys.path?

开发者 https://www.devze.com 2023-02-01 12:30 出处:网络
I\'m hoping there\'s an easy answer to this question that I\'m simply overlooking. Here\'s the setup: foo/

I'm hoping there's an easy answer to this question that I'm simply overlooking.

Here's the setup:

foo/
    __init__.py
    run.py

Contents of run.py:

import foo

Run the script:

$ python run.py 
Traceback (most recent call last):
  File "run.py", line 1, in <module>
    import foo
ImportError: No module named foo

The only way I can figure out to address this is:

Contents of run.py:

import sys
import os

path = os.path.abspath(__file__)
sys.path.append(os.path.join(os.path.dirname(path), "../"))

import foo
开发者_开发问答

So that works, but the problem (if I'm not mistaken) is that this adds the parent directory of foo/ to sys.path and thus searches all of the sibling folders of foo/ for Python modules.

There's a case I have where I really, really don't want to do that. I just want to add a single directory as a module to my path, but I can't figure out how to just add that module without adding that directory's parent directory and thus every other directory beneath that parent directory.

Am I overlooking something here? Is there an easy way I can add a script's parent folder as a module?


I don't quite see why run is meant to import its own parent package. After all, a package is just meant to be a way of collecting modules together; it's not meant to have significant functionality of its own.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other’s module names.

Are you sure you don't want run to import a sibling module? That you can do using relative imports.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号