不看script1.py、script2.py和script3.py的内容很难说。我猜每个模块中都有正在执行的顶级代码,而您不希望这种情况发生。
模块中的代码将在导入时执行。例如,如果 script1.py 包含以下内容:
# script1.py
def f():
print "not called on import"
# following will be executed on first import
print "print was executed"
x = 10
print x * x
导入它将导致:
>>> import script1
print was executed
100
函数中的代码没有被执行,但是声明函数的语句被执行了。
您可以通过检查__name__ 变量来阻止在导入时执行顶级代码,如下所示:
# script1.py
def f():
print "not called on import"
if __name__ == '__main__':
# following will NOT be executed on first import, only if run directly
print "print was executed"
x = 10
print x * x
>>> import script1
>>> script1.f()
not called on import
但是,如果直接执行script1.py会出现打印的内容:
$ python script1.py
print was executed
100
您问题的另一部分是用户如何调用在您的三个脚本文件中声明的函数?例如,您可以使用input() 而不是raw_input(),并让用户输入字符串script1.f()。
# main.py
import script1
import script2
import script3
if __name__ == '__main__':
input("write <module_name>.<name_of_the_function>() : ")
$ python main.py
write <module_name>.<name_of_the_function>() : script1.f()
not called on import