具有sudo权限的setuptools中的安装后脚本

2024-04-20 03:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试构建一个setup.py文件来将python脚本作为服务安装。到目前为止,我可以安装脚本,在systemd中手动添加一个单元,并启用/启动服务,但我想自动完成。我的问题是构建单元文件的bash脚本需要sudo权限,我不想用sudo运行pip install。你知道吗

import os
import subprocess
from setuptools import setup, Extension
import setuptools.command.install
from distutils.command.build import build as build_orig


class install(setuptools.command.install.install):
    def run(self):
        setuptools.command.install.install.run(self)
        current_dir_path = os.path.dirname(os.path.realpath(__file__))
        create_service_script_path = os.path.join(current_dir_path, 'bin', 'create_service.sh')
        subprocess.check_output([create_service_script_path])


setup(name='dspt',
      version=dspt.__version__,
      packages=['dspt'],
      include_package_data=True,
      package_data={"": ["data/template.xml"]},
      ext_modules=[ext],
      install_requires=['slackclient==1.3.1',
                        'numpy',
                        'numba',
                        'scipy',
                        'pytz',
                        'requests',
                        'pyjwt',
                        'pysmb',
                        'boto3'],
      cmdclass={
          'install': install
      },
      entry_points={'console_scripts': ['run_dspt = dspt.batch_processing:main']}
)

创建_服务.sh

#!/bin/bash
SYSTEMD_SCRIPT_DIR=$( cd  $(dirname "${BASH_SOURCE:=$0}") && pwd)
cp -f "$SYSTEMD_SCRIPT_DIR/dspt.service" /etc/systemd/system
chown root:root /etc/systemd/system/dspt.service

systemctl daemon-reload
systemctl enable dspt.service

单位文件

[Unit]
Description=My super service
After=multi-user.target network.target

[Service]
User=myuser
Group=mygroup
EnvironmentFile=/etc/environment
Type=idle
Restart=always
RestartSec=3
ExecStart=/home/myuser/miniconda3/envs/dspt/bin/run_dspt

[Install]
WantedBy=multi-user.target

注意,目前,单元文件假设包安装在名为dspt的conda虚拟环境中。你知道吗

bash脚本create_service.sh显然需要sudo特权,我不知道该怎么做。你知道吗


Tags: install文件pathrunimport脚本oscreate