如何从Python程序调用存储在其他文件中的函数?
如果我有一个文本文件,里面包含一个Python函数的定义,我该如何从另一个Python程序中调用这个函数呢?需要注意的是,这个函数会在调用它的Python程序中定义。
可以采取的方式有:
把这个Python函数当作一个模块来调用。不过这里有个限制,我需要把一个普通的Python函数转换成模块,这样会出错。
把函数的代码直接插入到调用这个函数的程序里。
哪种方式更好呢?
补充:感谢大家的回复,帮我澄清了我最初的困惑。还有一个疑问,如果有人(显然不是我)写了os.system("rm -rf"),我一不小心执行了,那对我来说就意味着末日,对吧?
补充2:因为很多人建议我使用exec,我想提到这个讨论帖,特别是关于命名空间的问题。这给用户很多机会去“规避”Python的限制。你们不觉得吗?
5 个回答
有没有类似于Java中的反射功能?如果有的话,Python有一个叫做imp的模块可以提供这样的功能。
foo.py
def foo():
return "return from function foo in file foo.py"
在任何地方的一些代码
modes = imp.get_suffixes() #got modes Explained in link below
mode = modes[-2] # because I want load a py file
with open("foo.py") as file:
m = imp.load_module("name", file, "foo.py", mode)
print(m.foo())
在mode = modes[-2]
之前,因为我的imp.get_suffixes()
是:
>>> imp.get_suffixes()
[('.cpython-32m.so', 'rb', 3), ('module.cpython-32m.so', 'rb', 3), ('.abi3.so', 'rb', 3), ('module.abi3.so', 'rb', 3), ('.so', 'rb', 3), ('module.so', 'rb', 3), ('.py', 'U', 1), ('.pyc', 'rb', 2)]
这是我的输出:
Python 3.2.1 (default, Aug 11 2011, 01:27:29)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import imp
>>> with open("foo.py") as file:
... m = imp.load_module("foo", file, "foo.py", ('.py', 'U', 1))
...
>>> m.foo()
'return from function foo in file foo.py'
你可以在这里查看: http://docs.python.org/py3k/library/imp.html 这个功能在Python 2.7和Python 3中都可以使用:
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import imp
>>> imp.get_suffixes()
[('.so', 'rb', 3), ('module.so', 'rb', 3), ('.py', 'U', 1), ('.pyc', 'rb', 2)]
>>> with open("foo.py") as file:
... m = imp.load_module("foo", file, "foo.py", ('.py', 'U', 1))
...
>>> m.foo()
'return from function foo in file foo.py'
compile() 和 eval() 可以解决这个问题:
>>> code = compile('def foo(a): return a*2', '<string>', 'exec')
>>> eval(code)
>>> foo
52: <function foo at 0x01F65F70>
>>> foo(12)
53: 24
或者可以用文件:
with open(filename) as source:
eval(compile(source.read(), filename, 'exec'))
你需要关注的是exec这个关键词。
>>> mycode = 'print "hello world"'
>>> exec mycode
Hello world
如果你把文本文件当作文本来读取(假设文件里只包含一个函数),可以这样做:
test.txt:
def a():
print "a()"
test.py:
mycode = open('test.txt').read()
exec mycode # this will execute the code in your textfile, thus define the a() function
a() # now you can call the function from your python file
文档链接:http://docs.python.org/reference/simple_stmts.html#grammar-token-exec%5Fstmt
你可能还想看看compile这个语句:这里.