Reputation: 14744
I'm trying to navigate between modules in Python but I can't return to main menu.
This is the arch: main.py
calls opa.py
and opb.py
main.py:
import sys, opa, opb
def menu():
print '1. Go opA'
print '2. Go opB'
print '3. Exit'
pick = raw_input('Pick one: ')
if pick == '1':
opa.menu()
elif pick == '2':
opb.menu()
else:
sys.exit()
menu()
opa.py:
def menu():
print '1. Speak'
print '2. Return'
pick = raw_input('Pick one: ')
if pick == '1':
print 'OpA'
elif pick == '2':
main.menu()
opb.py:
def menu():
print '1. Speak'
print '2. Return'
pick = raw_input('Pick one: ')
if pick == '1':
print 'OpB'
elif pick == '2':
main.menu()
When I pick 2 in opa.py
and opb.py
the program breaks with this error [in this case I go onto opa.py and select "2. Return"]:
Traceback (most recent call last):
File "main.py", line 16, in <module>
menu()
File "main.py", line 10, in menu
opa.menu()
File "opa.py", line 8, in menu
main.menu()
NameError: global name 'main' is not defined
If I add from main import menu
I get this other one:
Traceback (most recent call last):
File "main.py", line 1, in <module>
import sys, opa, opb
File "opa.py", line 1, in <module>
from main import menu
File "main.py", line 16, in <module>
menu()
File "main.py", line 10, in menu
opa.menu()
AttributeError: 'module' object has no attribute 'menu'
And I get it before loading opa.py or opb.py
Any suggestions?
SOLUTION: The arch was wrong, so I put the imports after the imports. Like that:
def menu():
print '1. Go opA'
print '2. Go opB'
print '3. Exit'
pick = raw_input('Pick one: ')
if pick == '1':
import opa
opa.menu()
elif pick == '2':
import opb
opb.menu()
else:
import sys
sys.exit()
menu()
Upvotes: 0
Views: 1552
Reputation: 5187
"The program breaks" is a bit unclear, but most likely you forgot to add imports of your main menu():
Insert import main
on top of your other files and it should do the trick.
Upvotes: 1