将 python 逆向转换为字符串
问题:是否可以将 python 对象逆向工程为字符串?
信息:我现在正在进行一个项目,该项目将我教授的研究成果分发到几十台计算机上,而不仅仅是他的。作为一名优秀的程序员,我正在使其成为一个通用程序,它不仅可以用于他的特定程序。因此,将运行他的代码的计算机不会也不会拥有他的 .py 文件供其导入。我过去解决这个问题的方法是,他只需将所有内容都放在一个文件中,并将该文件的路径传递到我的系统,然后将该代码从其状态作为字符串导入(使用从这个问题)。
但这让我想知道。我现在可以从字符串导入并使代码执行得很好。一切都很好,但这让我思考,有没有办法让我不必让他将代码文件传递给我?我特别想知道这样的事情。假设他的文件中包含所有这些内容:
def hello():
print "Hello world!"
导入此文件后,“hello”将被添加到全局命名空间中。但现在我想通过网络传输它。你不能在“hello”上调用pickle并使其工作,我已经尝试过,pickle出了正确的拒绝。
在另一端,我让节点计算机使用“exec code in newMod.dict”来创建代码。因此,如果我可以将“hello”推送到某个返回给我的函数“def hello():\n print \"Hello world!\””,以便我的 exec 方法可以运行。我会是金色的。然后我可以做到这一点,这样他就可以拥有不止 1 个文件,因为我可以对他拥有的任何非标准导入进行逆向工程。
老实说,我希望答案是否定的,但我认为值得一试。简单地说,我想获取一个已导入的模块并将其转换为字符串。
Question: is it possible to reverse engineer python objects into a string?
Info: I'm working on a project right now that distributes my prof's research across several dozen computers instead of just his. Being a good programmer I'm making it a generalized program that can be used for more than just his specific program. So the computers that will be running his code do not and will not have his .py files for them to import. The way I've gotten around this in the past is he just has to have everything in one file and pass the path to that file to my system which then imports that code as a from its state as a string (using the information gleaned from this question).
But that made me wonder. I can now import from a string and have the code execute fine and dandy. thats all well and good, but it made me think, is there a way for me to get around having to have him pass his code file to me? particularly I'm wondering something like this. say he has all of this in his file:
def hello():
print "Hello world!"
upon importing this file "hello" would be added to the global namespace. but now I want to transfer it across the network. you can't call pickle on "hello" and have it work, I've tried, pickle out right refuses.
on the other end I have the node computers using "exec code in newMod.dict" to get the code created. so if I could take "hello" and push it through some function that returns to me "def hello():\n print \"Hello world!\"" so that my exec method could then run. I would be golden. I could then make it so he could have more than just 1 file because I could just reverse engineer any non-standard imports he has.
I'm honestly expecting the answer to be no, but i figured it is worth a shot. Simply stated again, I want to take an module that has been imported and convert it into a string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然这不是一个好方法,但您可以仅从函数中pickle __code__ ...
Although it's not a good approach, you can pickle only the
__code__
from the function...使用 marshal 模块,您可以保留代码对象等等:
不确定这是否是一个好方法......
With marshal module you can persist code objects back and forth:
Not sure if this is a good approach though...