简体   繁体   English

如何在不知道路径的情况下从其他相关文件夹导入?

[英]How I can Import from a other relative folder wihout the knowledge of the path?

I am working on a little video game in Pygame.我正在 Pygame 中开发一个小视频游戏。 I want it to be very clear in the folder hierarchy, so, I've already prepare it in this way :我希望它在文件夹层次结构中非常清晰,因此,我已经以这种方式准备了它:

Python 
   Project 
      bin
        init.py
        Project.vbs
      lib
        constants.py
        definitions.py
      sprites ( useless for topic )
      Project.exe

The Project.exe is a ink file, a fake executable. Project.exe 是一个墨迹文件,一个伪造的可执行文件。 In fact, it's a shortcut to the Project.vbs with open the init.py (It's just for have the clearest folder managment).实际上,它是打开 init.py 的 Project.vbs 的快捷方式(它只是为了拥有最清晰的文件夹管理)。

What is my problem?我的问题是什么? I want to import the difinitions.py and the constants.py from the init.py which is in 'bin' folder, it's just absolutely critical for the game.我想从 'bin' 文件夹中的 init.py 导入 difinitions.py 和 constants.py,这对游戏来说绝对是至关重要的。 By The way, the files are saved on my USB key but the path of this one always change:顺便说一下,文件保存在我的 USB 密钥上,但这个路径总是改变:

On my own computer, it's C:/user/Save19/Python/...在我自己的电脑上,它是C:/user/Save19/Python/...

On my high school computers, it's P:/documents/Python ( internship )在我高中的电脑上,它是P:/documents/Python ( internship )

On my phone it's /storage/0/Python/...在我的手机上它是/storage/0/Python/...

And anytime I made a copy, the path change...每当我复制时,路径都会改变......

So I've read a lot of topics for try to fix that but anytime it's not working :/所以我已经阅读了很多主题来尝试解决这个问题,但无论何时它都不起作用:/

I've try it by using :我已经尝试过使用:

Import constants from lib import constants from lib.definitions import * I've try ths with the os and the path Import constants from lib import constants from lib.definitions import *我已经尝试过使用 os 和路径

import sys sys.path.insert(0, 'Project/lib') import constants

import sys sys.path.append('Project/lib') import constants

But it not working anyway... Can somebody give me a solution and explain me it?但无论如何它都不起作用......有人可以给我一个解决方案并向我解释吗?

It really depends from where you're starting the Python process.这实际上取决于您从何处开始 Python 进程。 Whatever path you're adding should be relative to that location.您添加的任何路径都应该相对于该位置。 So you say it's started from within bin and so you can add所以你说它是从bin内开始的,所以你可以添加

import os
import sys

sys.path.append(os.path.abspath('../lib'))
import constants

You can also add __init__.py to lib and then add ".." to path and do import lib.constants as constants .您还可以将__init__.py添加到lib ,然后将".."添加到 path 并import lib.constants as constants

Or you can setup and install the whole thing as a Python package and then use absolute imports such as import mygame.lib.constants as constants .或者,您可以将整个内容设置并安装为 Python 包,然后使用绝对导入,例如import mygame.lib.constants as constants

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

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