0

I'm trying to write a program which does a series of equations using two different sets of numbers. I have both sets of numbers saved as separate dictionaries. I would like to be able to choose which two dictionaries I use by inputting their names into the terminal using raw_input. Here's what I have written:

 def open():
     print "an opening text, description on what the program is actually doing"
     mathstart()

def mathstart():
     print "What is the first directory you wish you import?"
     'directory1' = raw_input("> ")
     import 'directory1'
     print "your first directory is" + 'directory1'[name]

All of the directories are formatted with a name, so I can confirm I'm using the correct one, and then a bunch of different data.

When I run the program from a terminal, I get the following error:

$ python engine.py
File "engine.py", line 11
import 'directory11'
SyntaxError: invalid syntax

This is unsurprising, since I completely guessed as to how I would be able to call the directory using raw_input.

My real question is, would I be able to do this, or is it something that doesn't work? Since I really don't want to have to go in add the directories into the code each time I have to use it. I have 20+ different directories that I need to interchange. That's just a pain.

If I can't select a directory with raw_input, is there a way to select one without having to change the code each time?

macfij
  • 3,093
  • 1
  • 19
  • 24
Xomen
  • 1

1 Answers1

0

A good discussion of dynamic module importing can be found here.

What you are trying to do could be accomplished using the __import__ function, which takes a string as an argument. For example:

def dynamic_import():
    print "What is the first directory you wish you import?"
    directory = raw_input("> ")
    directory = __import__(directory)

    return directory

my_module = dynamic_import()

Although it would likely be cleaner to pass the module as an argument to the function instead of using raw_input.

Community
  • 1
  • 1
Ewharris
  • 164
  • 3