Unable to use module in local folder - python-3.x

I am attempting to create an API wrapper but I am unable to use the wrapper. My __init__.py
from .sb import Skyblock
The folder that contains the module is called skyblock and the file with the Skyblock class is called sb.py
The file I'm trying to use the module in contains this code
from skyblock import *
set_api_key('49baa0d9-ecf3-430d-8669-c08495664889')
uuid = uname_resolver('Metasploitable')
print(get_news())
I am getting an undefined error
Here's the directory structure
C:.
| requirements.txt
| testing.py
|
\---skyblock
| sb.py
| __init__.py
|
\---__pycache__
sb.cpython-37.pyc
__init__.cpython-37.pyc

You are using relative import, so you need to import as
from .skyblock import *
You can refer to this site for more information: PEP-328

Related

Python ModuleNotFoundError while importing a module in conftest for Pytest framework

My project structure
mt-kart
|
--> src/data_kart
| |
| -->apis
| |
| -->__init__.py
| |
| -->main.py
--> tests
|
-->__init__.py
|
-->conftest.py
|
-->test_others.py
conftest.py has the following line.
from data_kart.main import fastapi_app
When run pytest from command line from project root(mt-kart). I get the following error
ModuleNotFoundError No module named 'data_kart'
How to make data_kart visible for conftest.py .
Option 1
Use relative imports:
from ..src.data_kart.main import fastapi_app
fastapi_app()
Please note, the above requires running conftest.py outside the project's directory, like this:
python -m mt-kart.tests.conftest
Option 2
Use the below in conftest.py (ref):
import sys
import os
# getting the name of the directory where the this file is present.
current = os.path.dirname(os.path.realpath(__file__))
# Getting the parent directory name where the current directory is present.
parent = os.path.dirname(current)
# adding the parent directory to the sys.path.
sys.path.append(parent)
# import the module
from src.data_kart.main import fastapi_app
# call the function
fastapi_app()
And if it happens for a module being outside the parent directory of tests, then you can get the parent of the parent direcory and add that one to the sys.path. For example:
parentparent = os.path.dirname(parent)
sys.path.append(parentparent)
Option 3
Same as Option 2, but shorter.
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from src.data_kart.main import fastapi_app
fastapi_app()
Option 4
Options 2 and 3 would work for smaller projects, where only a couple of files need to be updated with the code above. However, for larger projects, you may consider including the directory containing your package directory in PYTHONPATH, as described here (Option 3).

How to get a real path of a Python file in Project Directory

I am using an Automation project with following structure
C:\Project_Name\Scripts
Under script folder, I have my python automation modules, libraries and other required data folders.
But I want this project not only restricted to C: drive. I should seamlessly able to execute by scripts from any drive, any parent directory of "Project_Name" folder.
I have tried the following. But it is always not true if I try to trigger my test from jenkins.
os.path.join(os.path.dirname(os.path.abspath(__file__)))
Think about this tree:
Project
|
|--Scripts
| |
| |--__init__.py
| |--use_text.py
| |--text.txt
|
|--run_me.py
and imagine we have to get text.txt path in use_text.py
Step 1. in run_me.py get the path of project directory, and save it as a environ using os. (example:)
import os
from pathlib import Path
path = Path(__file__).parent # replace it with your preferred library's version
os.environ['PROJECT_BASE_DIR'] = str(path)
from Scripts.use_text import use
use()
now in use_text.py
import os
text_path = 'Scripts/text.txt'
project_path = os.getenv('PROJECT_BASE_DIR')
text_real_path = os.path.join(project_path, text_path)
def use():
# do whatever you want with text_real_path
I got a way to get the real path of the file no matter where the project directory been placed.
import os
os.path.join((os.path.realpath(__file__)).split("<Base Directory Name>")[0], "<relative path till the file>")
this worked as well, with simple path.

Python import from parent directory for dockerize structure

I have a project with two applications. They both use a mongo-engine database model file. Also they have to start in different Docker containers, but use the same Mongo database in the fird container. Now my app structure looks like this:
app_root/
app1/
database/
models.py
main.py
app2/
database/
models.py
main.py
And it works fine, BUT I have to support two same files database/models.py. I dont want to do this and I make the next structure:
app_root/
shared/
database/
models.py
app1/
main.py
app2/
main.py
Unfortunately it doesnt work for me, because when I try this in my main.py:
from ..shared.database.models import *
I get
Exception has occurred: ImportError
attempted relative import with no known parent package
And when I try
from app_root.shared.database.models import *
I get
Exception has occurred: ModuleNotFoundError No module named 'app_root'
Please, what do I do wrong?
In the file you perform the import, try adding this:
import os
import sys
sys.path.append(os.path.abspath('../../..'))
from app_root.shared.database.models import *

Relative Imports for two parents dir up

I have the following directory structure
code
|-----|--experiments
| |---v0
| |---agcnn.py
|-----|--pn
| |---bag
| |--run.py
run.py uses a module inside the agcnn.py. However when I try the import as following:
from experiments.v0.agccn import AG
it gives a relative import error saying no module. I'm using VScode and the the working dir is taken care by Vscode as root which is /code/ in this case.
How can I change the settings to accommodate the import ?

Python 3: Importing Files / Modules from Scattered Directories and Files

I have the following directory structure:
/home/pi
- project/
- p1v1.py
- tools1/
- __init__.py
- tools1a/
- __init__.py
- file1.py
- file2.py
- tools1a1/
- __init__.py
- file3.py
- file4.py
- tools1a2/
- __init__.py
- file5.py
- file6.py
I am trying to import all the modules from the file1.py into my project file p1v1.py
from file1 import *
but end up with either an
ImportError: attempted relative import with no known parent package
or an
ValueError: Attempted relative import in non-package
depending on what I use in p1v1.py because the functions in file1.py depend on file3.py and file4.py. I would like to use explicit imports (for clarity), but I'm not sure how to do this. Any advice would be appreciated.
Thank you!
Through trial and error eventually figured out how to solve this:
import sys
sys.path.insert(0,'..')
from tools1.tools1a.file1 import function as f1
Note: For this to work, I needed to be editing and executing my script p1v1.py out of the working directory /home/pi/project/. Hope this helps others with a similar problem!

Resources