我需要通过filepath导入
python模块(例如,“/some/path/to/module.py”),只在运行时知道并忽略任何.pyc文件.
这个previous question建议使用imp.load_module作为解决方案,但这种方法似乎也使用.pyc版本(如果存在).
importme.py
SOME_SETTING = 4
main.py:
import imp
if __name__ == '__main__':
name = 'importme'
openfile, pathname, description = imp.find_module(name)
module = imp.load_module(name, openfile, pathname, description)
openfile.close()
print module
执行两次,首次调用后使用.pyc文件:
$python main.py
$python main.py
不幸的是,imp.load_source具有相同的行为(来自文档):
Note that if a properly matching byte-compiled file (with suffix .pyc
or .pyo) exists, it will be used instead of parsing the given source
file.
让每个包含脚本的目录都是只读的是我所知道的唯一解决方案(首先防止生成.pyc文件),但如果可能的话我宁愿避免使用它.
(注意:使用python 2.7)