Skip to content

Instantly share code, notes, and snippets.

@leiless
Last active May 6, 2024 12:36
Show Gist options
  • Save leiless/20a94356f40fd7a214ca1204a574df55 to your computer and use it in GitHub Desktop.
Save leiless/20a94356f40fd7a214ca1204a574df55 to your computer and use it in GitHub Desktop.
import os
import sys
import zipfile
import shutil
def unzip_py_env(py_env_zip: str):
py_env_dir = py_env_zip.removesuffix('.zip')
need_update = not os.path.isdir(py_env_dir)
if not need_update:
with open(os.path.join(py_env_dir, '_tree.md5sum')) as f:
prev_hash = f.read().strip()
with zipfile.ZipFile(py_env_zip) as f:
curr_hash = f.read('_tree.md5sum').decode('utf-8').strip()
assert type(prev_hash) is type(curr_hash), f'{type(prev_hash)} vs. {type(curr_hash)}'
need_update = prev_hash != curr_hash
# Remove old pyenv directory
shutil.rmtree(py_env_dir)
if need_update:
os.makedirs(py_env_dir, mode=0o755, exist_ok=True)
with zipfile.ZipFile(py_env_zip) as f:
f.extractall(py_env_dir)
APP_NAME = 'your-py-app'
def py_env_setup():
parent_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
py_env = os.path.join(parent_dir, f'{APP_NAME}-pyenv')
if os.path.isfile(f'{py_env}.zip'):
unzip_py_env(f'{py_env}.zip')
# Modify Python search path
sys.path.append(py_env)
@leiless
Copy link
Author

leiless commented May 6, 2024

1-init-py-env.sh

#!/bin/bash

set -eufxo pipefail

cd "$(dirname "$0")"

NAME="$(basename "$PWD")-pyenv"
rm -rf "$NAME" "$NAME.zip"
# Use native pip to download and possibly build the packages
# see: https://stackoverflow.com/questions/65597206/importing-cython-generated-so-module-with-another-python-version-or-on-another/65598076#65598076
pip3.exe install -r requirements.txt -t "$NAME"

pushd "$NAME"
    find . -type f,l -printf "%h/%f %s\n" | cut -d/ -f2- | sort -V | md5sum | awk '{print $1}' > _tree.md5sum
    zip -qr "../$NAME.zip" .
popd

@leiless
Copy link
Author

leiless commented May 6, 2024

2-pack-to-py-exe.sh

#!/bin/bash

set -eufo pipefail
#set -x

cd "$(dirname "$0")"

NAME="$(basename "$PWD")"

python.exe -m \
    PyInstaller \
    --name "$NAME" \
    --onefile \
    --icon NONE \
    $NAME.py

mv "dist/$NAME.exe" .
rm -rf dist
chmod a+x "$NAME.exe"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment