Nat*_*urt 16 python distutils setup.py python-2.7
我正在使用带有Distutils的Python 2.7来分发和安装我自己创建的包.我的setup.cfg看起来像这样:
[install]
prefix=/usr/local/MODULENAME
record=installation.txt
Run Code Online (Sandbox Code Playgroud)
我有两个问题:
在定义其他setup.cfg选项时,是否可以引用setup.cfg中设置的变量(但也可以使用命令行选项)?例如,对于:
install-scripts=PREFIX/my-scripts
Run Code Online (Sandbox Code Playgroud)
我想PREFIX成为setup.cfg内部或使用--prefix命令行参数定义的前缀,类似于使用ConfigParser时的变量插值.
是否可以从我的setup.py中引用setup.cfg中设置的变量,而无需使用ConfigParser手动解析配置文件?
您可以参考文件中的其他变量/选项setup.cfg.语法是$variable,例如:
[install]
prefix = /my/prefix
install-scripts = $base/scripts
Run Code Online (Sandbox Code Playgroud)
请注意我使用,$base因为此变量受到在setup.cfg和使用setup.py install --prefix命令行选项中提供的前缀设置的影响.在这种情况下,/my/prefix/scripts除非用户使用命令行指定另一个前缀,否则将安装脚本.
也可以在$prefix内部使用setup.cfg,但这似乎不受自定义配置的影响.
setup())中访问变量值也可以读取您内部所有变量/选项的值setup.py.该函数setup返回类Distribution的实例.该类包含由命令(例如,安装)分组的变量的所有值,您可以使用该get_option_dict方法获取它们.例如:
#!/usr/bin/env python
from distutils.core import setup
d = setup(
# Here come your setup arguments
)
print(d.get_option_dict('install'))
Run Code Online (Sandbox Code Playgroud)
将打印:
{'prefix': ('setup.cfg', '/my/prefix'),
'install_scripts': ('setup.cfg', '$base/scripts')}
Run Code Online (Sandbox Code Playgroud)
setup())中访问变量值甚至可以在运行之前获得类Distribution的实例setup().为此,我们可以复制setup()内部正在进行的操作并自己构建该类的实例.然后,关于setup参数值的决定可以基于某些安装选项的值.我们来看一个例子:
from distutils.core import setup
from distutils.dist import Distribution
# Get our own instance of Distribution
dist = Distribution()
dist.parse_config_files()
dist.parse_command_line()
# Get prefix from either config file or command line
prefix = dist.get_option_dict('install')['prefix'][1]
print("Prefix is: " + prefix)
# Use the prefix to decide on the data path for data.txt
setup(data_files=[('/first/path/to/data' if prefix == '/some/prefix'
else '/second/path/to/data',
['data.txt'])])
Run Code Online (Sandbox Code Playgroud)