简体   繁体   中英

Importing packages and modules in Python from another folder

I have searched through the existing questions on stackoverflow and wasn't able to find what I am looking for. Firstly, I am new to Python, I come from Ruby so some things seem unclear to me in Python. I learn by doing so I am writing my own python REST API client for a payment gateway, which I plan on releasing to PyPi. The problem I have is importing modules from different folders. Let's say I have the folder structure like this:

my_project/src/lib/directory1/module1.py
my_project/src/lib/directory2/module2.py

In my_project/src/lib/directory1/module1.py I want to import a function defined in my_project/src/lib/directory2/module2.py so

# my_project/src/lib/directory2/module2.py
from lib.directory2 import module1

This doesn't work, it says ImportError: No module named directory2 . I read that in Python you need to add the module to the PATH but I have gone to PyPi and took the first library from the top ( SeleniumBase ) to look at how the code is organised in the GitHub project and I don't see they do any stuff like that. Could you please explain to me how this works and how I can organise my codebase to be able to import modules in one module from different folders to build my own library?

I read this article https://docs.python.org/3/reference/import.html and tried what they say in section 5.7. Package Relative Imports but it doesn't work

In theory this should work

from ..subpackage2.moduleZ import eggs

But it doesn't. I get SystemError: Parent module '' not loaded, cannot perform relative import .

Import will only work if the module you are trying to import is in the same directory as the script that is doing the import.

Otherwise you have to specify the path.

Like this :

import my_project/src/lib/directory1/module1.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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