簡體   English   中英

如何從 Python 中運行“python setup.py install”?

[英]How to run 'python setup.py install' from within Python?

我正在嘗試創建一個用於啟動 python 應用程序的通用 python 腳本,如果目標系統中缺少任何依賴的 python 模塊,我想安裝它們。 如何從 Python 本身運行與命令行命令 'python setup.py install' 等效的命令? 我覺得這應該很容易,但我無法弄清楚。

對於那些使用 setuptools 的人,您可以使用setuptools.sandbox

from setuptools import sandbox
sandbox.run_setup('setup.py', ['clean', 'bdist_wheel'])

閱讀本文: http//docs.python.org/distutils/apiref.html#distutils.core.run_setup

它有很好的記錄。

這對我有用(py2.7)
我在主項目的子文件夾中有一個帶有 setup.py 的可選模塊。

from distutils.core import run_setup [..setup(..) config of the main project..] run_setup('subfolder/setup.py', script_args=['develop',],stop_after='run')

謝謝

更新:
挖掘一段時間你可以在 distutils.core.run_setup 中找到

'script_name' is a file that will be run with 'execfile()'; 'sys.argv[0]' will be replaced with 'script' for the duration of the call. 'script_args' is a list of strings; if supplied, 'sys.argv[1:]' will be replaced by 'script_args' for the duration of the call.

所以上面的代碼應該改為

import sys
from distutils.core import run_setup
run_setup('subfolder/setup.py', script_args=sys.argv[1:],stop_after='run')

您可以使用子流程模塊:

import subprocess
subprocess.call(['python', 'setup.py', 'install'])
import os
string = "python setup.py install"
os.system(string)

嘗試這個

sudo apt install python-dev  # or python3-dev
pip install --user cython    # or pip3

然后

import os.path
from distutils.core import setup
from distutils.extension import Extension

from Cython.Distutils import build_ext
from Cython.Shadow import *  # This is important!

if __name__ == "__main__":
    setup(
        script_args=["build_ext", "--inplace"],  # Simulate CLI arguments
        cmdclass={'build_ext': build_ext},
        zip_safe=False,
        ext_modules=[
            Extension("hello",
                      ["hello.pyx"],
                      language='c++',
                      include_dirs=[os.path.dirname(__file__)])]  # Same folder
    )

如果hello.pyxinclude_dirs位於同一文件夾中,則運行上述腳本將在同一文件夾中放置一個hello.cpp和一個hello.so (Linux) 文件。 享受以編程方式調用 Cython 的樂趣。

那么就

#!/usr/bin/env python
import hello

參考: https : //cython.readthedocs.io/en/latest/src/quickstart/build.html

太晚了 - 但如果有人像我一樣發現他/她自己在這里 - 這對我有用; (蟒蛇3.4)。 我的腳本是 setup.py 的一個包。 請注意,我相信您必須在 setup.py 上使用 chmod +x。

cwd = os.getcwd()
parent = os.path.dirname(cwd)
os.chdir(parent)
os.system("python setup.py sdist")

只需導入它。

import setup

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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