Skip to main content

Full Python Interpreter Control and Bytecode Manipulation Library

Project description

mebytecode - Complete Python Interpreter Control Library

Hey there, my friend!

I'm mero, and I built this awesome library that I've been working on for days. It's called mebytecode and it gives you complete control over the Python interpreter from the inside out!

Hit me up on: Telegram @QP4RM
Check the code: https://github.com/6x-u/mebytecode
License: MIT - use it and modify it however you want
Version: 1.0.0


What's the deal with this library, bro?

Look, I'm not gonna bore you with a long story. This library is seriously powerful for controlling Python. You can execute code without writing it in a file, analyze bytecode, monitor programs while they're running, and basically control everything. But be careful! This library is powerful and dangerous at the same time.


Installation - Super easy

Quick way from PyPI

pip install mebytecode

Or from GitHub if you want the fresh code

git clone https://github.com/6x-u/mebytecode.git
cd mebytecode
pip install -e .

Git Repository and Using It

The code is stored on GitHub. Here's how you work with it:

Clone the repository

git clone https://github.com/6x-u/mebytecode.git
cd mebytecode

This downloads all the code and the entire history.

Check the branches

git branch -a

You'll see the different branches. The main branch is where the stable code lives.

See all the changes I made

git log --oneline

This shows you every change I committed with a short message about what changed.

Get detailed info about a specific commit

git show <commit-hash>

This shows you exactly what changed in that commit.

Update to the latest version

git pull origin main

This downloads the latest changes from the repository.

Check the status of your local copy

git status

This shows you if you have any uncommitted changes.

Create your own branch for modifications

git checkout -b my-feature

This creates a new branch where you can make changes without affecting the main code.

Save your changes locally

git add .
git commit -m "Description of what you changed"

Using the library in your projects

When you clone the repository, you get the source code directly. In your Python code, you can import it like this:

from mebytecode.xcore.interpreter import get_complete_interpreter
from mebytecode.zengine import BytecodeDisassembler
from mebytecode.vmonitor import get_monitor

ic = get_complete_interpreter()

Or if you installed it with pip, it works the same way. The library is immediately available.


What can you actually do?

First: Get info about Python and your system

First thing I do is create an object from the library:

from mebytecode.xcore.interpreter import get_complete_interpreter

ic = get_complete_interpreter()

Now you got your ic. This thing has all the functions you need.

info = ic.get_version_info()
print(f"Version: {info['major']}.{info['minor']}.{info['micro']}")

system = ic.get_platform_info()
print(f"System: {system['system']}")
print(f"Processor: {system['machine']}")
print(f"64-bit: {system['is_64bit']}")

get_version_info() returns a dictionary with Python version information. get_platform_info() tells you about the operating system and hardware.

Output:

Version: 3.11.13
System: Linux
Processor: x86_64
64-bit: True

Second: Execute code dynamically

I'm making code and executing it on the fly without writing it in a file. Imagine the possibilities!

from mebytecode.xcore.interpreter import get_complete_interpreter

ic = get_complete_interpreter()

code = ic.compile_code("""
x = 10
y = 20
z = x + y
print(f'Result: {z}')
""")

result = ic.execute_code(code)
print(f"Variables: {result}")

ic.compile_code() converts text into bytecode. ic.execute_code() runs that bytecode and returns all variables created.

Output:

Result: 30
Variables: {'x': 10, 'y': 20, 'z': 30}

Third: Evaluate mathematical expressions

answer = ic.evaluate_code("2 ** 10 + 5 * 3 - 10")
print(f"Calculation: {answer}")

This evaluates the expression and returns the result directly.

Result: 1015

Fourth: Work with functions

def add(a, b):
    return a + b

code_obj = ic.get_function_code(add)
print(f"Function name: {code_obj.co_name}")
print(f"Number of parameters: {code_obj.co_argcount}")

globals_dict = ic.get_function_globals(add)
print(f"Number of globals: {len(globals_dict)}")

get_function_code() gets the bytecode object of a function. get_function_globals() shows all global variables the function can access.

Fifth: Inspect objects and classes

class Car:
    def __init__(self, model):
        self.model = model
        self.speed = 0
    
    def accelerate(self):
        self.speed += 10
        return self.speed

car = Car("Toyota")

info = ic.inspect_object(car)
print(f"Type: {info['type']}")
print(f"Size in memory: {info['size']} bytes")
print(f"Attributes: {info['attributes']}")

methods = ic.get_object_methods(car)
properties = ic.get_object_properties(car)
print(f"Methods: {methods}")
print(f"Properties: {properties}")

inspect_object() gives you everything about an object. get_object_methods() shows what functions it has. get_object_properties() shows what data it stores.

Sixth: Capture output

capture, old_stdout = ic.capture_output()

print("This gets captured")
ic.print_to_stdout("And this too")

ic.restore_output(old_stdout)

output = capture.getvalue()
print(f"What got printed:\n{output}")

capture_output() redirects all printing to a container. restore_output() puts it back to normal. getvalue() gives you everything that was printed.

Seventh: Analyze bytecode

from mebytecode.zengine import BytecodeDisassembler

code_text = """
total = 0
for i in range(1, 6):
    total += i
"""

code = ic.compile_code(code_text)

info = ic.get_code_object_info(code)
print(f"Code name: {info['name']}")
print(f"Number of variables: {len(info['varnames'])}")

disasm = BytecodeDisassembler(code)
instructions = disasm.disassemble()
print(f"Instructions ({len(instructions)} total):")
for instr in instructions[:5]:
    print(f"  {instr.opname} -> {instr.argval}")

BytecodeDisassembler breaks down the bytecode into individual instructions that Python actually runs. You see the operation name and what value it uses.

Eighth: Control memory and garbage collection

print(f"GC enabled: {ic.is_gc_enabled()}")
print(f"Number of generations: {ic.get_gc_count()}")

collected = ic.force_gc()
print(f"Objects freed: {collected}")

ref_count = ic.get_reference_count(my_list)
print(f"Number of references: {ref_count}")

is_gc_enabled() checks if garbage collection is on. force_gc() cleans up unused memory right now. get_reference_count() tells you how many times a variable is referenced.

Ninth: Save and restore interpreter states

ic.save_state('checkpoint_1')

ic.set_recursion_limit(5000)
print(f"Recursion limit now: {ic.get_recursion_limit()}")

ic.restore_state('checkpoint_1')
print(f"Recursion limit restored: {ic.get_recursion_limit()}")

save_state() stores the current state. restore_state() puts everything back to how it was. Useful if you're experimenting and want to go back.

Tenth: Import modules dynamically

json_module = ic.import_module('json')
data = json_module.loads('{"name": "Ahmed", "age": 30}')
print(data)

import_module() loads a module at runtime. You can decide what to import based on what your program needs.


Real world usage examples

Example 1: Safe code execution from users

def safe_execute_user_code(user_code):
    try:
        code = ic.compile_code(user_code)
        result = ic.execute_code(code)
        return {'status': 'success', 'result': result}
    except:
        exc_type = ic.get_exception_type()
        exc_value = ic.get_exception_value()
        return {'status': 'error', 'type': exc_type.__name__, 'message': str(exc_value)}

result1 = safe_execute_user_code("x = 10 + 20")
print(result1)

result2 = safe_execute_user_code("x = 10 / 0")
print(result2)

This function lets you run code from users safely. If it fails, you get the error message without the program crashing.

Example 2: Performance testing

import time

def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

cpu_before = ic.get_cpu_times()
start_time = time.time()

result = fibonacci(20)

end_time = time.time()
cpu_after = ic.get_cpu_times()

print(f"Result: {result}")
print(f"Real time: {end_time - start_time:.4f} seconds")
print(f"CPU time: {cpu_after.user - cpu_before.user:.4f} seconds")

This shows you how long a function takes and how much processor time it uses. Useful for finding slow parts of your code.

Example 3: Deep code analysis

def analyze_function(func):
    code = ic.get_function_code(func)
    info = ic.get_code_object_info(code)
    
    print(f"Function: {info['name']}")
    print(f"Parameters: {code.co_argcount}")
    print(f"Local variables: {info['varnames']}")
    print(f"Stack size needed: {info['stacksize']}")
    print(f"Instructions: {len(info.get('bytecode', []))}")

def example_function(a, b, c):
    result = (a + b) * c
    return result

analyze_function(example_function)

This function shows you everything about how another function works internally. You see the parameters, local variables, and what instructions it needs.

Example 4: Monitoring execution

from mebytecode.vmonitor import get_monitor

monitor = get_monitor()

stats = monitor.get_stats()
print(f"Events processed: {stats['events_processed']}")
print(f"Errors recorded: {stats['errors']}")

state = monitor.get_state()
print(f"Monitor state: {state}")

The monitor keeps track of what's happening when programs run. You can check statistics about execution.


Important warnings - Read carefully

This library is powerful but also dangerous:

Don't execute code from people you don't trust - malicious code can destroy your system.

No warranty - I don't guarantee anything if something breaks. Read the LICENSE file for all the legal details.

You can lose data - backup your files before you experiment with this library.

Error system is complex - some errors don't have quick fixes. Not all situations can be recovered from.

Performance might be affected - this library uses system resources. Monitoring everything has a cost.


Tips for safe usage

Test in an isolated environment first. Don't test directly on production systems. Use a virtual machine or separate computer for experiments.

Check code before executing it. Put the code in a file and look at it carefully. Understand what it does before running it.

Use try and except blocks. Always wrap code execution in error handling. Don't let errors crash your program.

Backup your files. Before running the library, backup everything important. Keep multiple backups in safe places.

Read the source code. The library is open source. Look at the code to understand what it's really doing.


Questions and Answers

Q: Is this library safe? A: It's safe if you use it carefully. Just don't execute code from untrusted sources and always backup your data.

Q: Can I use it in big applications? A: Yeah, but test it well before putting it in production. Start with non-critical systems first.

Q: What if something breaks? A: Backup your data, try running the program again, and if it doesn't work contact me on Telegram.

Q: Can I modify the code? A: Yeah, the MIT license allows modifications. Just give me credit next to your name.

Q: Are there new updates coming? A: Hopefully yes. I'll push them to the GitHub repository when they're ready.

Q: How do I report bugs? A: Contact me on Telegram @QP4RM. Or create an issue on GitHub if you find something broken.

Q: Can I use this commercially? A: Yeah, the MIT license lets you use it for any purpose including commercial use.


Contact info

Me: mero Telegram: @QP4RM (if you have questions or problems) GitHub: https://github.com/6x-u/mebytecode License: MIT - use it freely Version: 1.0.0


Summary

I built this library with care and I hope you get good use out of it. The code is clean and the documentation is detailed, with lots of examples. Use it carefully and remember the warnings.

If you have any problems or questions, hit me up on Telegram @QP4RM.

Hope you do great things with this library.


mebytecode v1.0.0 - Complete Python Interpreter Control Library From my heart to your hands Best regards, mero

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mebytecode-4.0.3.tar.gz (87.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mebytecode-4.0.3-py3-none-any.whl (97.3 kB view details)

Uploaded Python 3

File details

Details for the file mebytecode-4.0.3.tar.gz.

File metadata

  • Download URL: mebytecode-4.0.3.tar.gz
  • Upload date:
  • Size: 87.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for mebytecode-4.0.3.tar.gz
Algorithm Hash digest
SHA256 e8281aa840e78a55d66fdf0639b3dfa4ec4947dd30536b367fa39f45da53156c
MD5 bd3c577327aeb6c3d35e8210769cc3f9
BLAKE2b-256 2cf7d7307eba61de749658f6194edf144879cbede7409482377976e484fcd69b

See more details on using hashes here.

File details

Details for the file mebytecode-4.0.3-py3-none-any.whl.

File metadata

  • Download URL: mebytecode-4.0.3-py3-none-any.whl
  • Upload date:
  • Size: 97.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for mebytecode-4.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 1db6660abe93d618cc231d0e2c6ed63026ffacfc75a229e61706880fbefb0816
MD5 0e0d9b1194fd7d5d859f066c3b33f7f6
BLAKE2b-256 880f65b66400c71082b50eed263f8a631279ebd37fa90430655e287e90c7144b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page