How do i run the python 'sdist' command from within a python automated script without using subprocess?

谁说胖子不能爱 提交于 2019-12-24 03:05:09

问题


I am writing a script to automate the packaging of a 'home-made' python module and distributing it on a remote machine.

i am using Pip and have created a setup.py file but i then have to call the subprocess module to call the "python setup.py sdist" command.

i have looked at the "run_setup" method in distutils.core but i am trying to avoid using the subprocess module alltogether. (i see no point in opening a shell to run a python command if i am already in python...)

is there a way to import the distutils module into my script and pass the setup information directly to one of its methods and avoid using the shell command entirely? or any other suggestions that may help me

thanks


回答1:


Just for the sake of completeness, I wanted to answer this since I came across it trying to find out how to do this myself. In my case, I wanted to be sure that the same python version was being used to execute the command, which is why using subprocess was not a good option. (Edit: as pointed out in comment, I could use sys.executable with subprocess, though programmatic execution is IMO still a cleaner approah -- and obviously pretty straightforward.)

(Using distutils.core.run_setup does not call subprocess, but uses exec in a controlled scope/environment.)

from distutils.core import run_setup

run_setup('setup.py', script_args=['sdist'])

Another option, may be to use the setuptools commands, though I have not explored this to completion. Obviously, you still have to figure out how to avoid duplicating your proj metadata.

from setuptools.dist import Distribution
from setuptools.command.sdist import sdist

dist = Distribution({'name': 'my-project', 'version': '1.0.0'}) # etc.
dist.script_name = 'setup.py'
cmd = sdist(dist)
cmd.ensure_finalized()
cmd.run()  # TODO: error handling

Anyway, hopefully that will help someone in the right direction. There are plenty of valid reasons to want to perform packaging operations programmatically, after all.




回答2:


If you don’t have a real reason to avoid subprocesses (i.e. lack of platform support, not just aesthetics (“I see no point”)), then I suggest you should just not care and run in a subprocess. There are a few ways to achieve what you request, but they have their downsides (like having to catch exceptions and reporting errors).



来源:https://stackoverflow.com/questions/9905743/how-do-i-run-the-python-sdist-command-from-within-a-python-automated-script-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!