I want my code to become unreadable. Let the person who wants to use it run it, but I don't want it to be able to open and read the code, how can I do that?
-
2You can compile it to an executable. – Barmar Jan 10 '22 at 23:59
-
3Or you could reimplement it in `perl`. :) – William Pursell Jan 11 '22 at 00:00
-
Is putting it on a server (e.g. making it a web service) an option? How about putting it in a shared Unix environment where other users have `+x` but not `+r` permission? If the user needs to be given the actual executable file, compilation/obfuscation is the best option, but these aren't bulletproof from a security/reverse-engineering perspective. – Samwise Jan 11 '22 at 00:04
2 Answers
What you are looking for is called code obfuscation.
It is not really possible in Python but as mentioned in this response you could compile your code to bytecode:
python -OO -m py_compile test.py
Example:
$ cat test.py
print("hello")
$
$ python3 -OO -m py_compile test.py
$
$ cat __pycache__/test.cpython-39.opt-2.pyc
a
?��a�@s
ed�dS)ZhelloN)�print�rr�test.py<module>�
$
$ python3 __pycache__/test.cpython-39.opt-2.pyc
hello
$

- 3,404
- 1
- 11
- 22
-
Note that when distributing compiled byte code, you need to run it with a matching version of python. – tdelaney Jan 11 '22 at 00:17
You can't exactly make it unreadable
There is no way to make it so the user can't read your file, but we can get close.
1. Executables
You can use pyinstaller as mentioned in this post.
It is very easy to compile, and you can use the command shown below:
Make sure you install it!
pyinstaller [options] script [script …] | specfile
// or
pyinstaller
2. Byte Code
As @Gab mentioned, you can compile to byte code.
This a great solution as you don't need any external downloads, but the problem is that you must run it with the matching version of python. (Pointed out by @tdelaney).
If you want to use this solution, follow @Gab's post. (It's pretty great)
3. Shared Unix Environment
As @Samwise said, you can use a shared unix environment.
How about putting it in a shared Unix environment where other users have
+x
but not+r
permission?
+x
- Execute
+r
- Read
4. Just don't do it.
There is really no reason for you to do this.
The only reason I can think of is if you are making this paid, and don't want people to make illegal copies. In that case, you can use this post (It's about gamedev, though some of the ideas are consistant)
Good luck with your script!