像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'
能否請你改一下你的問題?很難理解你想要做什麼。 –
我在文本文件中有一個python函數。例如:def abc(a,b):.. return a。這個函數必須從另一個Python程序中調用。 python函數本身不是程序或模塊。我正在努力進一步解釋它。 – Hick
它爲什麼不在.py文件中?畢竟他們只是文本文件! – Johnsyweb