🐕

pythonパッケージの中身をpydファイルにする

2024/04/06に公開

pythonが入ったパッケージからpydファイルを作成する。

Nuitkaをインストール

pip install nuitka

pythonで対象ファイルをpydファイルに変換

する。

import sys, os, shutil

args = sys.argv

folder_path = args[1]
output_directory = args[2]
folder_path = os.path.abspath(folder_path)
output_directory = os.path.abspath(output_directory)

def process_directory(directory, output_directory):
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        relative_path = os.path.relpath(file_path, folder_path)
        output_path = os.path.join(output_directory, relative_path)

        if os.path.isfile(file_path):
            if file_path.endswith('.py') and not os.path.basename(file_path) in ['__init__.py']:
                # Pythonファイルの場合、pydファイルを作成
                command = f'python -m nuitka --module "{file_path}"'
                os.system(command)
                print(filename)
                #作業ディレクトリを出力
                print(os.getcwd())
                shutil.move(filename.replace('.py', '.cp37-win_amd64.pyd'), output_path.replace('.py', '.pyd'))
                shutil.move(filename.replace('.py', '.pyi'), output_path.replace('.py', '.pyi'))
            else:
                # Pythonファイル以外の場合、ファイルをコピー
                shutil.copy2(file_path, output_path)
        else:
            # ディレクトリの場合、再帰的に処理
            os.makedirs(output_path, exist_ok=True)
            if not os.path.basename(file_path) in ['__pycache__']:
                process_directory(file_path, output_directory)

process_directory(folder_path, output_directory)

実行

$folder_path = Read-Host -Prompt 'Input your folder path'
$output_directory = Read-Host -Prompt 'Input your output directory'

python convert.py $folder_path $output_directory

buildの後の使わないCファイルとかも残るからよしなに消したりしてください。

Discussion