setup.py - 安装后将模块符号链接到 /usr/bin

2 投票
3 回答
3229 浏览
提问于 2025-04-18 12:20

我快完成一个Python包的开发了,也写了一个基本的setup.py文件,使用了distutils工具:

#!/usr/bin/env python
#@author: Prahlad Yeri
#@description: Small daemon to create a wifi hotspot on linux
#@license: MIT
import cli

#INSTALL IT
from distutils.core import setup
setup(name='hotspotd',
    version='0.1',
    description='Small daemon to create a wifi hotspot on linux',
    license='MIT',
    author='Prahlad Yeri',
    author_email='prahladyeri@yahoo.com',
    url='https://github.com/prahladyeri/hotspotd',
    package_dir={'hotspotd': ''},
    packages=['hotspotd'],
    data_files=[('config',['run.dat'])],
    )

#CONFIGURE IT

这个脚本现在运行得很好,能把需要的文件安装到指定的文件夹里。例如,下面这个命令:

sudo python setup.py install --prefix /opt

会把我的整个包安装到:

/opt/lib/python2.7/site-packages/hotspotd

不过,我希望主要的可执行文件hotspotd.py能链接到/usr/bin目录下的一个合适的文件,比如:

/usr/bin/hotspotd

这样用户就可以直接通过输入 hotspotd start 来启动我的程序,而不是通过Python间接调用。

我该如何修改setup.py来实现这个呢?如果我在setup()调用之后写复制代码,它每次都会被调用。我只想在程序安装的时候执行这个操作。

3 个回答

0

现在可以在 setuptools 中指定入口点了:

setup(
# other arguments here...
entry_points={
    'console_scripts': [
        'foo = my_package.some_module:main_func',
        'bar = other_module:some_func',
    ],
    'gui_scripts': [
        'baz = my_package_gui:start_func',
    ]
}

)

2

现在你应该使用 console_scripts 来让你的脚本放到 /usr/bin 这个地方。格式是:

from setuptools import setup

setup(
    ...
    console_scripts=[
        'hotspotd = hotspotd:my_main_func',
    ],
    ...
)
4

只需像这样使用 scripts 参数:

#!/usr/bin/env python
#@author: Prahlad Yeri
#@description: Small daemon to create a wifi hotspot on linux
#@license: MIT
import cli

#INSTALL IT
from distutils.core import setup
setup(name='hotspotd',
    version='0.1',
    description='Small daemon to create a wifi hotspot on linux',
    license='MIT',
    author='Prahlad Yeri',
    author_email='prahladyeri@yahoo.com',
    url='https://github.com/prahladyeri/hotspotd',
    package_dir={'hotspotd': ''},
    packages=['hotspotd'],
    data_files=[('config',['run.dat'])],
    scripts=["scriptname"], # Here the Magic Happens
    )

#CONFIGURE IT

现在,文件 scriptname 会被复制到 /usr/bin/scriptname,而文件开头的那一行(叫做 shebang)会被调用 setup.py 脚本的 Python 版本替换掉。所以,写你的脚本时要好好考虑哦。

撰写回答