我正在尝试编写一个程序,该程序使用两组不同的数字来执行一系列方程式。我将这两组数字保存为单独的词典。我希望能够通过使用raw_input将其名称输入终端来选择我使用的两个词典。这是我写的:
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]
所有目录都使用名称格式化,因此我可以确认我使用的是正确的目录,然后是一堆不同的数据。
当我从终端运行程序时,出现以下错误:
$ python engine.py
File "engine.py", line 11
import 'directory11'
SyntaxError: invalid syntax
这并不奇怪,因为我完全猜到了如何使用raw_input调用目录。
我真正的问题是,我能够做到这一点,还是它不起作用?因为每次我必须使用它时,我真的不想将目录添加到代码中。我有20多个不同的目录需要交换。这只是一种痛苦。
如果我无法使用raw_input选择目录,是否可以选择一个目录而无需每次更改代码?
答案 0 :(得分:0)
可以找到有关动态模块导入的详细讨论here。
您尝试做的事情可以使用__import__
函数来完成,该函数将字符串作为参数。例如:
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()
虽然将模块作为参数传递给函数而不是使用raw_input
可能会更清晰。