导入脚本并执行用户需要的脚本

时间:2014-08-06 13:36:22

标签: python function command-line import

我有三个脚本,它们都是一个或几个函数 我有另一个导入它们的脚本,但是当我运行它时,它会运行其他三个脚本(一个接一个)

import script1
import script2
import script3
#import sys 
#he i have some other lines but they just dont work

in=raw_input("write python+name_of_this_file+name_of_the_function")
#i do not know how to continue

我该怎么做才能运行这个脚本并执行用户想要的文件,我不太了解python(三个脚本花了我很多东西来制作它们) 提前谢谢你

2 个答案:

答案 0 :(得分:0)

如果没有看到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

答案 1 :(得分:0)

如何动态导入python模块并调用一个如果它的功能?

使用importlib.import_module()。例如,

import importlib

response = raw_input("Please type module_name function_name: ")
module_name, function_name = response.split()
print "User entered module_name %r, function_name %r" % (module_name, function_name)

try:
    module = importlib.import_module(module_name)
    result = getattr(module, function_name)()
    print "%s.%s() returned %r" % (module_name, function_name, result)
except ImportError, e:
    print "Failed to import module %r" % module
except AttributeError, e:
    print "Function %r not found in module %s" % (function_name, module_name)