假设您有一个包含Python脚本路径的字符串,并且您希望以透明的方式加载和执行该脚本(因此与通过"python path"直接运行相比,内部脚本没有根本区别).然后得到由此产生的全局字典.我认为runpy.run_path()会这样做,但有两个问题.如果路径包含某些unicode字符,则它不起作用(请参阅http://bugs.python.org/issue17588).最重要的是,鉴于全局字典只是原始字典的副本,因为当临时模块对象被垃圾收集时,这个原始字典被清除.所以函数对象已经损坏__globals__ dict(参见http://bugs.python.org/issue18331).
你有任何想法如何运行内部脚本?
更新:请参阅我目前的方法 - http://bpaste.net/show/RzAbQxLNXiJsXYm2fplz/.有什么建议?改进?例如,关于正在运行的脚本的观点可能有什么不同的细节.我知道有关realoading __main__的问题.
导入模块会在顶层执行代码,并且该模块的“全局”命名空间将作为模块的名称导入
james@bodacious:~$cat test.py
def func():
pass
myname = "michael caine"
print "hello, %s" % myname
james@bodacious:~$python
Python 2.7.5 (default, Jul 12 2013, 18:42:21)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
hello, michael caine
>>> dir(test)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'func', 'myname']
>>>
Run Code Online (Sandbox Code Playgroud)
如果您想要运行的代码位于文件的顶层,则只需导入模块即可执行代码并让您可以访问其“全局”命名空间,所有这些都在一个方便的包中。如果您要运行的代码不在顶层(例如,如果它位于main()仅通过常见技巧触发的函数中if __name__=="__main__"),您可以自己调用该函数:
james@bodacious:~$cat test.py
def main():
print "hello there!"
if __name__=="__main__":
main()
james@bodacious:~$python
Python 2.7.5 (default, Jul 12 2013, 18:42:21)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.main()
hello there!
>>>
Run Code Online (Sandbox Code Playgroud)
当然,有可能你要导入的文件不在sys.path中,所以不能简单地用import. 一个简单的解决方案可能是操作sys.path,但是如何导入给定完整路径的模块?描述了更好的解决方案imp.load_source()
| 归档时间: |
|
| 查看次数: |
1533 次 |
| 最近记录: |