Created
February 13, 2026 19:03
-
-
Save ahhh/a540d6c540e6add8d1c4051067b59e49 to your computer and use it in GitHub Desktop.
For messign with python file pickling
This file contains hidden or 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
| import argparse | |
| import base64 | |
| import pickle | |
| import ast | |
| import sys | |
| def pickle_data(input_data: str) -> str: | |
| """ | |
| Takes a Python literal string, converts to object, | |
| pickles it, and returns Base64 encoded string. | |
| """ | |
| try: | |
| # Safely evaluate Python literal (dict, list, etc.) | |
| obj = ast.literal_eval(input_data) | |
| except Exception as e: | |
| print(f"Error parsing input data: {e}") | |
| sys.exit(1) | |
| pickled = pickle.dumps(obj) | |
| encoded = base64.b64encode(pickled).decode() | |
| return encoded | |
| def depickle_data(encoded_string: str): | |
| """ | |
| Takes Base64 string, decodes and depickles it. | |
| """ | |
| try: | |
| decoded = base64.b64decode(encoded_string) | |
| obj = pickle.loads(decoded) | |
| return obj | |
| except Exception as e: | |
| print(f"Error depickling data: {e}") | |
| sys.exit(1) | |
| def depickle_and_repickle(encoded_string: str) -> str: | |
| """ | |
| Depickles then repickles the object. | |
| """ | |
| obj = depickle_data(encoded_string) | |
| repickled = pickle.dumps(obj) | |
| return base64.b64encode(repickled).decode() | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Pickle / Depickle CLI Tool") | |
| group = parser.add_mutually_exclusive_group(required=True) | |
| group.add_argument("-p", "--pickle", action="store_true", help="Pickle input data") | |
| group.add_argument("-d", "--depickle", action="store_true", help="Depickle Base64 input data") | |
| parser.add_argument("-i", "--input", required=True, help="Input string") | |
| args = parser.parse_args() | |
| if args.pickle: | |
| result = pickle_data(args.input) | |
| print("Pickled (Base64):") | |
| print(result) | |
| elif args.depickle: | |
| obj = depickle_data(args.input) | |
| print("Depickled object:") | |
| print(obj) | |
| # Also show repickled result | |
| repickled = depickle_and_repickle(args.input) | |
| print("\nRe-pickled (Base64):") | |
| print(repickled) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment