5

我需要一个 Python 等价于 PHP 的 include 函数。我知道 execfile(),但这不一样。有任何想法吗?

4

2 回答 2

11

尝试import,使用 try/except on ImportError

try:
    import modulename
except ImportError:
    print 'importing modulename failed'

没有抓住ImportError它就相当于require, sorta-kinda。

请注意,python 只会执行一次模块代码(使其更像是一个include_onceorrequire_once语句。当然,模块中的函数可以多次调用。

于 2012-06-28T01:36:19.863 回答
3

如果您想要在脚本中将字符串变量设置为外部文件a la php 的内容(示例 #6 Using output buffering to include a PHP file into a string ...),那么这可能有效:

s = open('file.abc').read()
于 2012-06-28T01:40:38.310 回答