Pythonのpycだけで実行する
Python3でどうしても.pyファイルを提供せずに実行できるようにしたい場合、.pycを生成して実行できる。
ただし、.pycがあればロジックは解析できちゃうので気休め程度。
.pycから.pyを逆生成するツールもある
元のソースは手に入らないけど、disでbytecodeを読むよりは読みやすい
実行例
ソース
code:main.py
import sub
sub.run('hello')
code:sub.py
def run(msg):
print(msg, 'world!')
compileall でpycを作るとき、 __pycache__ を無効化するため -b オプションを指定する
code:shell
$ python3 -m compileall -b main.py sub.py
Compiling 'main.py'...
Compiling 'sub.py'...
$ ls
main.py main.pyc sub.py sub.pyc
$ rm main.py sub.py
$ python3 main.pyc
hello world!
PEP 3147 -- PYC Repository Directories に __pycache__ のままでは.pyなしで実行できない話がある
pycからpyを復元
decompyle6を使う例
code:shell
(venv) $ pip install uncompyle6
(venv) $ uncompyle6 main.pyc sub.pyc
# uncompyle6 version 3.6.2
# Python bytecode 3.8 (3413)
# Decompiled from: Python 3.8.0 (v3.8.0:fa919fdf25, Oct 14 2019, 10:23:27)
# Clang 6.0 (clang-600.0.57)
# Embedded file name: main.py
# Size of source mod 2**32: 28 bytes
import sub
sub.run('hello')
# okay decompiling main.pyc
# uncompyle6 version 3.6.2
# Python bytecode 3.8 (3413)
# Decompiled from: Python 3.8.0 (v3.8.0:fa919fdf25, Oct 14 2019, 10:23:27)
# Clang 6.0 (clang-600.0.57)
# Embedded file name: sub.py
# Size of source mod 2**32: 39 bytes
def run(msg):
print(msg, 'world!')
# okay decompiling sub.pyc
# decompiled 2 files: 2 okay, 0 failed
このくらい単純なソースだとそのまま復元された。