This is my project structure:
maths/
__init__.py
trig.py
coord.py
pitch.py
models/
__init__.py
model.py
In model.py, I have:
import sys
sys.path.append("../")
from maths.pitch import *
if __name__ == "__main__":
# my routines
In pitch.py, I have:
from trig import calculate_distance_angles
When I run model.py, I'm getting the error:
File "model.py", line 38, in <module>
from maths.pitch import *
File "../maths/pitch.py", line 9, in <module>
from trig import calculate_distance_angles
ModuleNotFoundError: No module named 'trig'
How do I fix this?
The error came from here: from trig import calculate_distance_angles. I suppose you are looking for your maths/trig.py file:
maths/
__init__.py
trig.py <-- this one
coord.py
pitch.py
models/
__init__.py
model.py
On your sys.path, you may have this:
(all the original sys.path stuff)...
"../" (added at model.py)
But the maths model, as far as we can see, is not on sys.path. If that's true, you may have to modify the import as follows. This should work:
from maths.trig import calculate_distance_angles
Related
This is the structure of my project at the moment.
classes/
├─ __init__.py
├─ card.py
├─ find.py
├─ player.py
├─ table.py
.gitignore
main.py
My __init__.py:
from .card import *
from .player import *
from .table import *
The problem is when I want to import from example player to table.py,
like this:
from classes import Player
from classes import Card, CardType, CardValue, HandValue
I get the following error message:
Traceback (most recent call last):
File "/home/adrian/Desktop/Programozas/Poker/classes/table.py", line 1, in <module>
from classes import Player
ModuleNotFoundError: No module named 'classes'
Do you have any idea?
Notice that this error is occurring in ".../classes/table.py", line 1, as you are trying to import classes.Player when both table.py and player.py are contained in classes. To do this in table.py, you would use from .player import Player just like you did in __init__.py (instead of from classes import Player).
Anything at the same level or above classes can be done using this method, but anything defined inside classes cannot call up to classes, as anything therein does not even know classes exists.
Edit: if you need to be able to run both main.py and table.py, you could do something like:
# in table.py
try:
from player import Player # this should work when running table.py directly
except:
from .player import Player # this should work when running main.py (it's a relative import)
I have the following code structure:
Graph API/
│── main.py
├── helper_functions/
├── defines.py
├── insights.py
insights.py imports 2 functions from defines.py at the beginning:
from defines import getCreds, makeApiCall
It then uses "makeApiCall" for this function:
def getUserMedia( params ) :
// Some code about url endpoints etc.
return makeApiCall( url, endpointParams, params['debug'] ) # make the api call
I want to use the getUserMedia function in the main.py script, so I import it with:
from helper_functions.insights import *
But I get the error:
Traceback (most recent call last):
File "/Users/Graph_API/main.py", line 1, in <module>
import helper_functions.insights
File "/Users/Graph_API/helper_functions/insights.py", line 1, in <module>
from defines import getCreds, makeApiCall
ModuleNotFoundError: No module named 'defines'
What leads to this error? When I use the getUserMedia function within insights.py it works fine. I already tried importing defines.py to main.py as well, but I get the same error.
I am pretty new to programming, so I would really appreciate your help :)
You should replace
from defines import getCreds, makeApiCall
With
from helper_functions.defines import getCreds, makeApiCall
Or
from .defines import getCreds, makeApiCall
You must give a path either from project directory as in the first example, or from the relative path from the insights file by adding a dot.
You could also consider adding init.py to the helper_functions folder. Checkout here: What is __init__.py for?
I have a folder structure similar to this (my example has all the necessary bits):
web-scraper/
scraper.py
modules/
__init__.py
config.py
website_one_scraper.py
Where config.py just stores some global variables. It looks a bit like:
global var1
var1 = "This is a test!"
Within website_one_scraper.py it looks like this:
import config
def test_function():
# Do some web stuff...
return = len(config.var1)
if __name__ == "__main__":
print(test_function)
And scraper.py looks like this:
from module import website_one_scraper
print(website_one_scraper.test_function())
website_scraper_one.py works fine when run by itself, and thus the code under if __name__ == "__main__" is run. However, when I run scraper.py, I get the error:
ModuleNotFoundError: No module named 'config'
And this is the full error and traceback (albeit with different names, as I've changed some names for the example above):
Traceback (most recent call last):
File "c:\Users\User\Documents\Programming\Work\intrack-web-scraper\satellite_scraper.py", line 3, in
<module>
from modules import planet4589
File "c:\Users\User\Documents\Programming\Work\intrack-web-scraper\modules\planet4589.py", line 5, in
<module>
import config
ModuleNotFoundError: No module named 'config'
Also note that In scraper.py I've tried replacing from modules import website_one_scraper with import website_one_scraper, from .modules import website_one_scraper, and from . import website_one_scraper, but they all don't work.
What could the cause of my error be? Could it be something to do with how I'm importing everything?
(I'm using Python 3.9.1)
In your website_scraper_one.py, instead of import config.py try to use from . import config
Explanation:
. is the current package or the current folder
config is the module to import
In the following structure:
src:
model:
- boardmodel.py
- tests.py
exceptions:
- exceptions.py
- visual.py
I'm running visual.py from the terminal. In my boardmodel.py, I have the following import:
from exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError
This line causes an error when running visual.py:
Traceback (most recent call last):
File "visual.py", line 3, in <module>
from model.boardModel import Board
File "/Users/sahandzarrinkoub/Documents/Programming/pythonfun/BouncingBalls/balls/src/model/boardModel.py", line 5, in <module>
from exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError
ModuleNotFoundError: No module named 'exceptions'
What is the correct way to solve this problem? Should I change the import statement inside boardmodel.py to from model.exceptions.exceptions import ZeroError....? That doesn't feel like a sustainable solution, because what if I want to use boardmodel.py in another context? Let me her your thoughts.
EDIT:
I changed the structure to:
src:
model:
- __init__.py
- boardmodel.py
- tests.py
exceptions:
- __init__.py
- exceptions.py
- visual.py
But still I get the same error.
Place an empty file called __init__.py in each of the subdirectories to make them packages.
See What is __init__.py for? for more details
Then, within boardmodel.py you need to either use relative imports
from .exceptions.exceptions import ...
or absolute ones (from the root of PYTHONPATH)
from model.exceptions.exceptions import ...
When you execute a script from the command line, the directory containing the script is automatically added to your PYTHONPATH, and becomes the root for import statements
You are not at the root of your package so you need relative import.
Add a dot before exceptions:
from .exceptions.exceptions import ZeroError, OverlapError, ArgumentError, ProximityError
One dot mean "from the current directory"…
I got the following file structure:
/sound
__init.py
toplevelmain.py
/filters
__init__.py
vocoder.py
/effects
__init__.py
echo.py
/main
__init__.py
x.py
main.py
/main2
__init__.py
main2.py
File Contents are as follows
x.py:
def print_x():
print "X"
echo.py:
def print_echo():
print "ECHO"
vocoder.py:
from effects import echo
from main import x
def print_vocoder():
print "VOCODER"
echo.print_echo()
x.print_x()
toplevelmain.py:
#! /usr/bin/python
import filters.vocoder
filters.vocoder.print_vocoder()
main.py and main2.py have both the same code:
#! /usr/bin/python
if __name__ == '__main__':
if __package__ is None:
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from filters.vocoder import print_vocoder
else:
from ..filters.vocoder import print_vocoder
print_vocoder()
The Problem:
If I execute toplevelmain.py or main2.py everything works fine. However if I execute main.py which has the same code as main2.py I get the following exception:
File "./main.py", line 9, in <module>
from filters.vocoder import print_vocoder
File "/home/tg/sound/filters/vocoder.py", line 3, in <module>
from main import x
File "/home/tg/sound/main/main.py", line 14, in <module>
print_vocoder()
NameError: name 'print_vocoder' is not defined
What happens here and how can I alter main2.py in order to keep the file structure?
Is this problem solved in Python 3.x?
It is an import loop.
You imported main.x in filters.vocoder, and imported filters.vocoder in main.main.
When you are running main2/main2.py, there is no import loop. That's why you can run it without error.
You need to update your code to remove one import in the two files.