简体   繁体   English

Python 从远离 main() 的文件导入模块

[英]Python import module from a file very far from main()

I have a folder structure of Python files that looks like so:我有一个 Python 文件的文件夹结构,如下所示:

folder w space
       ├── folder1
       │      └── subfolder1
       │              └── file_1.py *is main*
       └── folder2
              └── folder w space2
                       └── file_2.py
                       └── __init__.py

I'm needing to have file_1.py (file that has main) import file_2.py as a package.我需要将file_1.py (具有主文件的文件)导入file_2.py作为 package。 Notice that file_2.py , in relation to file_1.py , is 3 directories up and then 3 directories down.请注意,与file_2.py相关的file_1.py是 3 个目录,然后是向下 3 个目录。 I would, in theory, write the relative import as so:理论上,我会这样写相对导入:

from ...folder2 import folder w space2.file2

However this is not valid due to the spacing in the subfolder.但是,由于子文件夹中的间距,这是无效的。 An absolute import is even worse because the base folder contains spaces too:绝对导入更糟糕,因为基本文件夹也包含空格:

import folder w space.folder2.folder w space2.file2 

With this, how can I import file_2.py as a module without:有了这个,我怎样才能将file_2.py作为一个模块导入,而不需要:

  1. Renaming the folders (I don't own them so I can't even if I wanted to)重命名文件夹(我不拥有它们,所以即使我想也不能)
  2. Without using sys.path.append() (does not work in our production env)不使用sys.path.append() (在我们的生产环境中不起作用)
  3. Moving file_2.py (for organization must stay where it is)移动file_2.py (因为组织必须留在原处)
  4. Hopefully not install any further libraries (isn't absolutely necessary but it would be a whole process for me to add new libraries to our production env)希望不要安装任何其他库(不是绝对必要的,但我将新库添加到我们的生产环境中将是一个完整的过程)

Any help would be immensely appreciated!任何帮助将不胜感激!

Even if you could rewrite the imports to be able to run this with spaces in the folder names your relative/absolute imports would blow for other reasons.即使您可以重写导入以便能够使用文件夹名称中的空格运行它,您的相对/绝对导入也会因其他原因而崩溃。 Remove the spaces from the folder names (make so they are valid python identifiers) and then run your main as:从文件夹名称中删除空格(使它们成为有效的 python 标识符),然后将 main 运行为:

$ cd "folder w space"
$ py -m folder1.subfolder1.file_1

This will make python see the folders as packages (cause its scans the current working dir) and is the recommended way of running a python script.这将使 python 将文件夹视为包(因为它会扫描当前工作目录),并且是运行 python 脚本的推荐方式。 Your imports will work out of the box:您的导入将开箱即用:

from ...folder2 import folder_w_space2.file2 # or
import folder2.folder_w_space2.file2 

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

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