python3 import not finding module - python

I'm trying to test out an example from a book and I'm getting an ImportError.
The example starts out like:
from tkinter import *
from PP4E.Gui.Tools.widgets import frame, button, entry
And if I put an import sys; print(sys.path) at the beginning of the code, the output is
['/Users/aaa/Documents/workspace/programming-python/PP4E/Lang/Calculator',
'/usr/local/lib/python3.4/site-packages/setuptools-12.2-py3.4.egg',
'/usr/local/lib/python3.4/site-packages/pip-6.0.8-py3.4.egg',
'/User/aaa/Documents/workspace/programming-python',... ]
This is what a truncated version of my programming-python directory looks like:
❯ tree
.
├── PP4E
│   ├── __init__.py
│   ├── Gui
│   │   ├── Tools
│   │   │   ├── __init__.py
│   │   │   └── widgets.py
│   │   └── __init__.py
│   ├── Lang
│   │   └── Calculator
│   │      ├── __init__.py
│   │      └── calc0.py
└── site-packages
└── PP4E.pth
The error message I'm getting is:
❯ python3 calc0.py
Traceback (most recent call last):
File "calc0.py", line 2, in <module>
from PP4E.Gui.Tools.widgets import frame, button, entry
ImportError: No module named 'PP4E'
Does anybody know what I have to do to get Python to find the PP4E module? Thanks.

I had my PYTHONPATH wrong -- the root directory is /Users, not /User. Thanks.

Related

Import error while running specific test case

Before I say something, let me show the current project hierarchy. The app name is api.
── api
│   ├──
│   ├── admin.py
│   ├── apps.py
│   ├── init.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── 0002_wallet_customer_id.py
│   │   ├── 0003_auto_20201201_1103.py
│   │   ├── 0004_auto_20201203_0703.py
│   │   ├── 0005_auto_20201207_1355.py
│   │   ├── __init__.py
│   │ 
│   ├── models.py
│   ├── permissions.py
│   ├── serializers.py
│   ├── stellar.py
│   ├── te_s_ts_bk.py
│   ├── te_sts_2.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── debug.log
├── manage.py
└── myapp
├── __init__.py
├── asgi.py
├── settings-local.py
├── settings-remote.py
├── settings.py
├── urls.py
└── wsgi.py
As it was suggested here, I even removed __init__.py file from the api app folder, yet having the issue.
My TestCase Class look like below:
class CreateWalletTestCase(APITestCase):
app_id = 0
app = None
def test_create_wallet(self):
response = self.client.post(
'/wallets/',
data={'app_id': self.app_id, 'customer_id': 'A-001'},
**{'HTTP_api_key': 'test-api', 'HTTP_api_secret': 'test-api-password'}
)
data = json.loads(response.content)
self.assertEqual(data['status'], 'OK
When I run as python manage.py test api.CreateWalletTestCase.test_create_wallet or even python manage.py test CreateWalletTestCase.test_create_wallet, it generates the error:
ImportError: Failed to import test module: CreateWalletTestCase
Traceback (most recent call last):
File "/usr/local/lib/python3.9/unittest/loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
ModuleNotFoundError: No module named 'api.CreateWalletTestCase'
The way to call the tests in python is very similar to the way you import things in that language. For example, if you want to import that TestCase in your file and assuming it is in the tests.py file, you should write import CreateWalletTestCase from api.tests in the elegant way. You can also write import api.tests.CreateWalletTestCase, to import it.
So, to call that specific test, you should write the command in the following way:
python manage.py test api.tests.CreateWalletTestCase.test_create_wallet
You can check the Django Documentation here about running tests.
It is not necessary to delete the __init__.py file.

Cant import module from script in same/other directories

Directory structure:
.
├── classification
│   ├── lstm_repres.py
│   ├── lstm_test.py
│   ├── lstm_train.py
│   ├── lstm_utils.py
│   ├── lstm_utils.pyc
│   └── svm_run.py
├── utils
│   ├── data_splits.py
│   ├── evaluation.py
│   ├── load_data.py
│   ├── NLTKPreprocessor.py
│   ├── resources.py
│   ├── TfIdf.py
│   └── vector_utils.py
at lstm_train.py:
from classification.lstm_utils import *
when i try to run with both python2 lstm_train.py or python3 lstm_train.py, i get:
Traceback (most recent call last):
File "classification/lstm_train.py", line 7, in <module>
from classification.lstm_utils import *
ModuleNotFoundError: No module named 'classification'
The same happens at the line
from utils.data_splits import get_train, get_val
What is the issue here? Why does the format from <dir>.<script> import * doesn't seem to be working here?
EDIT
As suggested by #deathangel908, I've added __init__.py empty files to both directories, but the error persists.
In order to mark directory as a package you want to import, it needs to have least empty __init__.py within that directory. So add __init__.py files to classification and utils directories.
In order to import absolute path package you need to run python interpreter from the root package as a module: python3 -m "classification.lstm_train"

Flask from .models import * giving "attempted relative import with no known parent package"

When in my app.py, I am trying to import something from models.py and when I use
from .models import *
but I'm receiving the following error on my shell
ImportError: attempted relative import with no known parent package
My directory tree looks as following:
└── PROJECT_FOLDER
├── README.md
├── __pycache__
│   ├── app.cpython-36.pyc
│   ├── app.cpython-38.pyc
│   ├── scraping.cpython-36.pyc
│   └── scraping.cpython-38.pyc
├── app.py
├── db.sqlite3
├── models.py
├── scraping.py
├── static
│   └── css
│   ├── bootstrap-theme.min.css
│   ├── bootstrap.min.css
│   ├── sign.css
│   └── theme.css
└── templates
├── base.html
└── index.html
I've tried putting a main.py in an outer folder and importing from PROJECT_FOLDER.models import *
but that hasn't worked.
I also have tried putting an __init__.py in my root directory.
Any help is appreciated. Thanks!

Python: AttributeError module x has no attribute y

I have a project with directory structure like below
.
├── Pipfile
├── Pipfile.lock
├── module
│   ├── __init__.py
│   ├── helpers
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   └── __init__.cpython-36.pyc
│   │   ├── dynamo.py
│   │   └── logger.py
│   └── test.py
Relavant code
logger.py
import click
import sys
from tabulate import tabulate
def formatter(string, *rest):
return string.format(*rest)
def info(*rest):
"""Write text in blue color
"""
click.echo(click.style('☵ ' + formatter(*rest), fg='blue'))
test.py
import helpers
helpers.logger.info('Trying')
When I try to run using the command
python3 module/test.py
I get this error
Traceback (most recent call last):
File "module/test.py", line 4, in <module>
helpers.logger.info('Trying')
AttributeError: module 'helpers' has no attribute 'logger'
I have tried restructuring the code. Putting the helpers directory outside, in level with module directory. But still it didn't work, which it should not have, from what I have read. I tried researching a bit about __init__.py and python module system. The more I read, the more confusing it gets. But from whatever I learned, I created another sample project. With the following structure,
.
└── test
├── __init__.py
├── helpers
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   └── quote.cpython-36.pyc
│   └── quote.py
├── index.py
├── logger
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   └── info.cpython-36.pyc
│   └── info.py
Code is same as first project.
Here when I do,
python3 test/index.py
It works as expected. The only difference between the two projects:
In the first project, I used pipenv to install deps and create virtual environment.
Using your initial layout (with loggers as a submodule of the helpers package), you'd need to explicitely import loggers in helpers/__init__.py to expose it as an attribute of the helpers package:
# helpers/__init__.py
from . import logger
logger is module and not attribute and helpers.logger evalutes logger as attribute. Actually you should do as follow:
from helpers import logger
print(logger.info('Trying'))

Python/Django: import weirdness

I've the following project setup
....
├── lira
│   ├── __init__.py
│   ├── admin.py
│   ├── ajax.py
│   ├── authentication.py
│   ├── context_processors.py
│   ├── fencoder
│   │   ├── __init__.py
│   │   ├── encoder.py
│   │   ├── ffmpeg_commands.py
│   │   ├── frames.py
│   │   ├── utils.py
│   │   └── video.py
│   ├── models.py
....
And when I try to import from lira.fencoder import encoder I get an error ImportError: cannot import name encoder.
What is wrong with the above project setup though this morning it was the same and it worked?
Sultan
If you want to debug import problems, sometimes a simple launch of
python -v -m path/to/python/module/to_start
will help you, it will show you all the imports done by the python interpreter and help detect cyclic imports.

Categories

Resources