I'm trying to create a generic python script for starting up a python app and I would like to install any dependent python modules if they are missing from the target system. How can I run the equivalent of the command line command 'python setup.py install' from within Python itself? I feel like this should be pretty easy, but I can't figure it out.
8 Answers
For those, who use setuptools you can use setuptools.sandbox :
from setuptools import sandbox
sandbox.run_setup('setup.py', ['clean', 'bdist_wheel'])
3 Comments
Run a distutils setup script, sandboxed in its directoryYou can use the subprocess module:
import subprocess
subprocess.call(['python', 'setup.py', 'install'])
2 Comments
This works for me (py2.7)
I have a optional module with its setup.py in a subfolder of the main project.
from distutils.core import run_setup
[..setup(..) config of the main project..]
run_setup('subfolder/setup.py', script_args=['develop',],stop_after='run')
Thanks
Update:
Digging a while
you can find in 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.
so the above code shold be changed to
import sys
from distutils.core import run_setup
run_setup('subfolder/setup.py', script_args=sys.argv[1:],stop_after='run')
1 Comment
import os
string = "python setup.py install"
os.system(string)
1 Comment
Try this
sudo apt install python-dev # or python3-dev
pip install --user cython # or pip3
Then
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
)
If you have hello.pyx in the same folder as include_dirs, then running the above script will place a hello.cpp and a hello.so (Linux) file in the same folder. Enjoy programmatically calling Cython.
Then just
#!/usr/bin/env python
import hello
REF: https://cython.readthedocs.io/en/latest/src/quickstart/build.html
Comments
Just import it.
import setup
2 Comments
Way late - but if someone finds him/herself here like I did - this worked for me; (python 3.4). My script was one package down from setup.py. Note, you have to have chmod +x on setup.py, I believe.
cwd = os.getcwd()
parent = os.path.dirname(cwd)
os.chdir(parent)
os.system("python setup.py sdist")