Last active
July 23, 2021 08:05
-
-
Save hsinhoyeh/67125e2759ed3daf19e6c3facf27fa4a to your computer and use it in GitHub Desktop.
serialize/deserialize python function with dill and base64
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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