Directly call distutils' or setuptools' setup() function with command name/options, without parsing the command line?

假如想象 提交于 2019-12-05 02:58:37

Never tried this, but I did happen to look in distutils/core.py, where I notice this near the start of setup():

if 'script_name' not in attrs:
    attrs['script_name'] = os.path.basename(sys.argv[0])
if 'script_args' not in attrs:
    attrs['script_args'] = sys.argv[1:]

So, it looks as if you can "fake-out" setup() by adding:

setup(
    ...
    script_name = 'setup.py',
    script_args = ['bdist_rpm', '--spec-only']
)

Just "fake" the commandline parameters -- e.g, start you script with

import sys

sys.argv[1:] = ['bdist_rpm', '--spec-only']

from distutils.core import setup

setup(name='Distutils',

etc, etc. After all, that's how distutils gets the command line parameters: it looks in sys.argv! So, just set sys.argv to be exactly as you want it, and whatever command line the misguided user typed will be completely ignored.

Actually, you might want to check if the user did enter any argument you're about to ignore -- len(sys.argv) > 1 before you modify sys.argv -- and give a warning, or avoid the alteration of sys.argv, or "merge" what the user typed, etc... but that's quite different from what you actually asked, so I'm going to leave it at that;-).

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