Monday, May 6, 2024
HomePythonRecovering misplaced Python supply code if it’s nonetheless resident in-memory

Recovering misplaced Python supply code if it’s nonetheless resident in-memory


I learn this on GitHub Gist the opposite day. I don’t know whether or not I’ll ever use it however I’m nonetheless placing this on my weblog for the sake of bookmarking it. Who is aware of? Somebody from the viewers would possibly find yourself utilizing it!

I screwed up utilizing git (git checkout – on the unsuitable file) and managed to delete the code I had simply written… nevertheless it was nonetheless operating in a course of in a docker container. Right here’s how I received it again, utilizing pyrasite and uncompyle6

Connect a shell to the docker container

Set up GDB (wanted by pyrasite)

apt-get replace && apt-get set up gdb

Set up pyrasite – it will allow you to connect a Python shell to the still-running course of

pip set up pyrasite

Set up uncompyle6, which is able to allow you to get Python supply code again from in-memory code objects

pip set up uncompyle6

Discover the PID of the method that’s nonetheless operating

ps aux | grep python

Connect an interactive immediate utilizing pyrasite

pyrasite-shell <PID>

Now you’re in an interactive immediate! Import the code you could get well

>>> from my_package import my_module

Work out which capabilities and courses you could get well

>>> dir(my_module)
['MyClass', 'my_function']

Decompile the operate into supply code

>>> import uncompyle6
>>> import sys
>>> uncompyle6.major.uncompyle(
    2.7, my_module.my_function.func_code, sys.stdout
)
# uncompyle6 model 2.9.10
# Python bytecode 2.7
# Decompiled from: Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
# [GCC 5.4.0 20160609]
# Embedded file title: /srv/my_package/my_module.py
function_body = "seems right here"

For the category, you’ll must decompile every technique in flip

>>> uncompyle6.major.uncompyle(
    2.7, my_module.MyClass.my_method.im_func.func_code, sys.stdout
)
# uncompyle6 model 2.9.10
# Python bytecode 2.7
# Decompiled from: Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
# [GCC 5.4.0 20160609]
# Embedded file title: /srv/my_package/my_module.py
class_method_body = "seems right here"

I hope you guys like this submit. Keep tuned for the following one within the upcoming days.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments