0

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
  • 115,751
  • 26
  • 228
  • 437
  • 2
    You've got to learn about writing and `import`ing modules. – DYZ Feb 23 '18 at 23:14
  • Is this another python script? If so, see what @DyZ says above. If it's some other language, a shell call can work if there isn't a better solution. – Kyle Feb 23 '18 at 23:15
  • why the indentation is so wide? – Jason Hu Feb 23 '18 at 23:17
  • Well, thanks i've found. I've just written import name_of_the_other_file but when i test my script, it executes me directly this other file. Or i wanna do it only if the user selects it – a.lejeune626 Feb 23 '18 at 23:19
  • Note [PEP-8](https://www.python.org/dev/peps/pep-0008/), and strongly consider starting with Python 3.x (or at least compatible syntax like `except ValueError as e:` rather than `except ValueError, e:`). – jonrsharpe Feb 23 '18 at 23:34
  • 1
    In addition to what others have said, it's probably worth checking [this, regarding `if __name__ == '__main__'`](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) out. – ChootsMagoots Feb 23 '18 at 23:48

1 Answers1

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