Skip to content

Instantly share code, notes, and snippets.

@hsinhoyeh
Last active July 23, 2021 08:05
Show Gist options
  • Save hsinhoyeh/67125e2759ed3daf19e6c3facf27fa4a to your computer and use it in GitHub Desktop.
Save hsinhoyeh/67125e2759ed3daf19e6c3facf27fa4a to your computer and use it in GitHub Desktop.
serialize/deserialize python function with dill and base64
# background: when you run python code with command mode (aka -c ), inspect module can't work well as it didn't
# serialize commands into .py file. instead we can leverage dill to handle marshal or unmarshal functions for us.
# in this example, we wrap it into a python declarator.
# pip install dill
def inspectMe(f):
import dill as pickle
import base64
def wrapper(*arg, **kwargs):
with open('temp_code.py', 'w') as w:
code_str = pickle.dumps(f)
w.write(base64.b64encode(code_str).decode('utf-8'))
f()
return wrapper
def decodeMe():
import dill as pickle
import base64
with open('temp_code.py', 'r') as r:
byte_code = r.read()
f = pickle.loads(base64.b64decode(byte_code.encode()))
f()
@inspectMe
def foo():
print('bar')
foo()
print('decoding...')
decodeMe()
#
#run with shell
#
#```shell
#python3 -c "$(cat inspecttest.py)"
#```
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment