簡體   English   中英

使用 Python 自動啟動安裝包

[英]Autostart installed package with Python

給定一個包含hello.py random.whl

print("Hello World!")

有沒有辦法創建一個setup.pysetup.cfgpyproject.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM