1

I have compiled this visible_code.py file into .pyc compiled byte code file, then I am running the function fun from .pyc file.

# visible_code.py

def fun():
    print("Hello")
# convet to bytecode
import py_compile
py_compile.compile("visible_code.py", "secret_code.pyc")

Then I am deleting this file called visible_code.py and trying to run the function fun from secret_code.pyc in main.py file.

# main.py
from secret_code import fun
fun()

Everything works perfect until I change the python version, I get error regarding magic numbers. I have used this image from a different file structure.

enter image description here

Is there is any way that I can create this secret_code.pyc file for all the python version or at least python3. How to get rid of this magic numbers error.

Visrut
  • 360
  • 4
  • 14
  • 4
    Not possible. You have to compile new pyc with each Python interpreter. – wim Nov 11 '22 at 16:11
  • Why do you want to remove the .py file ?, The .pyc is trivially turned back to .py if you know the magic number (and sometimes without it), which you should know to run the code anyway, so using .pyc file instead of .py has no advantage in terms of code obfuscation. – Ahmed AEK Nov 11 '22 at 16:14
  • @AhmedAEK I want to hide my code from end user so is there is any way we can achieve this in python? I know they can reverse engineer, but I want to just hide at first. – Visrut Nov 11 '22 at 16:15
  • The magic number is there because the bytecode meaning changes incompatibly when the magic number changes. If you could get rid of the magic number, it would just cause other things to break. – Charles Duffy Nov 11 '22 at 16:19
  • @wim thanks do you know any reason as well why this behavior? – Visrut Nov 11 '22 at 16:19
  • If there _weren't_ a magic number, Python upstream couldn't change the bytecode in backwards-incompatible ways; that would make the interpreter harder to maintain, and for no good reason. If you want to obfuscate, obfuscate _your source_. – Charles Duffy Nov 11 '22 at 16:20
  • @CharlesDuffy is there is another way to create a file, but end user can't see source code directly? – Visrut Nov 11 '22 at 16:21
  • 1
    [How to obfuscate Python code effectively?](https://stackoverflow.com/questions/3344115/how-to-obfuscate-python-code-effectively) – Charles Duffy Nov 11 '22 at 16:21
  • 1
    ...really, though, there's no such thing as effective obfuscation. If a user can run it on a general-purpose computer they control, they can inspect what that computer is doing. (There's thesis-level research work on encrypted computation, but I'll believe it as practical reality only when I see it). – Charles Duffy Nov 11 '22 at 16:22
  • 1
    Among the above-linked question's answers, though, see in particular https://stackoverflow.com/a/58979147/14122 and https://stackoverflow.com/a/68214794/14122 – Charles Duffy Nov 11 '22 at 16:24

0 Answers0