Reputation: 501
And although this was asked a MILLION times, this case is special, because either I am very dumb, or my laptop is.
So to make sure that everybody is on the same page, here is what I want to do: use import menu
inside of fish life imulator.py
, and here is the file tree that I did:
fish_life_simulator
fish_life_simulator.py
extra_programs
__init__.py
menu.py
And I tried EVERYTHING that I found, os.chdir
redirect to the extra programs folder, sys.path.append
or sys.path.insert
, import file
or from file import def
, __init__.py
as you can see, but I always seem to get the same error: ModuleNotFoundError: No module named 'menu'
Edit: here is a sample of my code:
fish_life_simulator
import pygame, random, time, sys, os
from pygame.locals import *
os.chdir(os.path.dirname(__file__))
pygame.init()
size_of_monitor = pygame.display.Info()
flags = RESIZABLE
width = size_of_monitor.current_w - 25
height = size_of_monitor.current_h - 50
from extra_programs import menu
screen, screen_size, menu_background_image, menu_background_stretched_image, menu_background_rect = initiation(width, height, flags)
menu.py
def initiation(width, height, flags):
screen = pygame.display.set_mode((width, height), flags)
screen_size = screen.get_size()
menu_background_image = pygame.image.load(r'sprites\menu_background.jpg')
menu_background_stretched_image = pygame.transform.scale(menu_background_image, (screen_size))
menu_background_rect = menu_background_stretched_image.get_rect()
return screen, screen_size, menu_background_image, menu_background_stretched_image, menu_background_rectscreen, screen_size, menu_background_image, menu_background_stretched_image, menu_background_rect
Upvotes: 1
Views: 139
Reputation: 1848
I got it to work with the following folder structure and the following code:
fish_life_simulator
|-- extra_programs
| |-- __init__.py
| `-- menu.py
`-- fish_life_simulator.py
menu.py
def menu():
print("hello from menu")
fish_life_simulator.py
from extra_programs import menu
menu.menu()
There is no need at all to edit the path or something like that.
Just navigate into the folder fish_life_simulator
and run the code with python fish_life_simulator.py
.
If you don't want to type the menu.
prefix, you can adapt fish_life_simulator.py
like below:
from extra_programs.menu import menu
menu()
In your code, you are lacking the prefix, when calling initiation(...)
, it should be menu.initiation(...)
. You need to decide for one of the above ways to import.
Upvotes: 1
Reputation: 15568
Inside a folder fish_life_simulator
execute
PYTHONPATH=. python fish_life_simulator.py
Where in fish_life_simulator.py
your import are
from extra_programs import menu
...
Or one level outside folder fish_life_simulator
execute
PYTHONPATH=fish_life_simulator/ python fish_life_simulator/fish_life_simulator.py
Where in fish_life_simulator.py
your import are
from fish_life_simulator.extra_programs import menu
...
Upvotes: 2