我有一个资源很少的系统(嵌入式)。因此,我只为我的程序安装了 python .pyo 文件(=字节编译和优化)。现在,当这样的程序运行时,python 会不断寻找 .py 文件(可能是为了查看 .pyo 是否需要更新)。有趣的是,它做了很多次:5 分钟内 25000 次 stat64() 调用(和 8304 次 getcwd 调用())!
getcwd("/tmp", 1026) = 9
getcwd("/tmp", 1026) = 9
stat64("MyProgram.py", 0xbeb94b0c) = -1 ENOENT (No such file or directory)
stat64("/usr/local/lib/python2.5/MyProgram.py", 0xbeb94b0c) = -1 ENOENT (No such file or directory)
stat64("/usr/local/lib/python25.zip/MyProgram.py", 0xbeb94b0c) = -1 ENOENT (No such file or directory)
stat64("/usr/local/lib/python2.5/MyProgram.py", 0xbeb94b0c) = -1 ENOENT (No such file or directory)
stat64("/usr/local/lib/python2.5/plat-linux2/MyProgram.py", 0xbeb94b0c) = -1 ENOENT (No such file or directory)
stat64("/usr/local/lib/python2.5/lib-tk/MyProgram.py", 0xbeb94b0c) = -1 ENOENT (No such file or directory)
stat64("/usr/local/lib/python2.5/lib-dynload/MyProgram.py", 0xbeb94b0c) = -1 ENOENT (No such file or directory)
stat64("MyProgram.py", 0xbeb94cc8) = -1 ENOENT (No such file or directory)
getcwd("/tmp", 1026) = 9
stat64("MyProgram.py", 0xbeb94bc4) = -1 ENOENT (No such file or directory)
我怎样才能阻止Python这样做呢?
答案1
您可以尝试更换__builtins__.__import__
函数(由 import 语句调用)与您自己的代码。您可以使用imp.load_module
函数加载 py/pyc/pyo 文件。
这是它的一个非常简单的版本:
import sys
import imp
real_import = __builtins__.__import__
def pyc_only_import(name, globals = globals(), locals = locals(), fromlist = [], level = 0):
pycname = name + ".pyc"
modfile = open(pycname)
return imp.load_module(name, modfile, pycname, (".pyc", "rb", 2))
__builtins__.__import__ = pyc_only_import
import hello
这远未完全实现,__import__
但如果当前工作目录中有 hello.pyc 文件,它就可以工作。