How to execute compiled python code

最后都变了- 提交于 2019-12-01 23:35:36

问题


I have a compiled Python file, path/program.pyc.

I want to execute it with my current globals() and locals(). I tried:

with open('path/program.pyc','rb') as f:
   code = f.read()
   exec(code, globals(), locals())

More specifically, what I want to have is:

a.py:

a = 1
# somehow run b.pyc

b.py:

print(a)

When I run a.py, I want to see the output: 1.

Actually execfile() does exactly what I want, but it only works for .py files not .pyc files. I am looking for a version of execfile() that works for .pyc files.


回答1:


There may be a better way but using uncompyle2 to get the source and execing will do what you need:

a = 1

import uncompyle2
from StringIO import StringIO
f = StringIO()
uncompyle2.uncompyle_file('path/program.pyc', f)
f.seek(0)
exec(f.read(), globals(), locals())

Running b.pyc from a should output 1.




回答2:


Use __import__ https://docs.python.org/2/library/functions.html#import

Note that you need to use standard python package notation rather than a path and you will need to make sure your file is on sys.path

Something like __import__('path.program', globals(), locals()) should do the trick.



来源:https://stackoverflow.com/questions/32259786/how-to-execute-compiled-python-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!