I want to know if it's possible to import/include a script into other one?
In my case, my main script asked simply a choice from the user. And according to this choice, I want to include the other script.
print (30 * '-')
print (" M A I N - M E N U")
print (30 * '-')
print 'Information'
print (30 * '-')
print ("1. Choice 1")
print ("2. Choice 2")
print ("3. Choice 3")
print (30 * '-')
is_valid=0
while not is_valid :
try :
choice = int ( raw_input('Enter your choice [1-3] : ') )
is_valid = 1 ## set it to 1 to validate input and to terminate the while..not loop
except ValueError, e :
print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
if choice == 1:
# Here I want to include the other script from other file.
jonrsharpe
123k31 gold badges278 silver badges489 bronze badges
1 Answer 1
As DyZ said, take a look at importing modules.
as a simple example, suppose that you have the following folder structure
- src/
- main.py
- moduleA/
- __init__.py
- menu.py
If you run the above code under src, you can import menu.py in main.py like:
from moduleA import menu
ps.: arguments can be easily parsed with: https://docs.python.org/3.3/library/argparse.html
answered Feb 23, 2018 at 23:21
Arthur Marques
631 silver badge7 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
a.lejeune626
Thanks, no, i've not this structure. Well, now, i know how to do it.
Arthur Marques
@a.lejeune626 nice! As I'm trying to improve my rank, could you please mark the solution if it worked for you?
lang-py
importing modules.if __name__ == '__main__'out.