[英]Autostart installed package with Python
給定一個包含hello.py
random.whl
print("Hello World!")
有沒有辦法創建一個setup.py
, setup.cfg
或pyproject.toml
,當執行時,會以每次啟動 Python 時都會執行hello.py
的方式安裝包?
pip install random.whl
python unrelated.py # First prints "Hello World", then continues on.
我知道可以掛鈎 Python 自動加載的readline.py
,但是有沒有一種不同的、不那么“hacky”的方式來實現它?
我想到的一些不可能的方法:
.whl
發行版上運行安裝后腳本(安裝后僅在sdist
上可用)。PYTHONSTARTUP
變量或復制文件。雖然存在安全風險,但實現它的方法有利於實現調試器或審計工具,而無需更改預編譯或后編譯的 Python 代碼,或用於邊信道攻擊中的滲透測試。
到目前為止,使用sitecustomize.py
並使用自定義install
命令發布sdist
是最可靠的,並且與usercustomize.py
或.pth
文件不同,它在虛擬環境中工作。
相關setup.py
代碼:
import sys
import os
import setuptools
import sysconfig
from setuptools.command.install import install
class PreInstall(install):
def run(self):
site_packages_dir = sysconfig.get_path("purelib")
sitecustomize_path = os.path.join(site_packages_dir, "sitecustomize.py")
if os.path.exists(sitecustomize_path):
raise FileExistsError("Site customize file already exists. "
"Please remove it before installing.")
install.run(self)
setuptools.setup(
name='...',
version='0.0.1',
py_modules=["sitecustomize"],
cmdclass={'install': PreInstall,},
)
它仍然不適用於.whl
發行版,因為它可能會覆蓋現有的sitecustomize
而無法檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.