Start a python script at startup automatically?

前端 未结 1 375
故里飘歌
故里飘歌 2021-01-14 18:48

I followed multiple tutorials available on stackoverflow about starting a python script at startup but none of them works.

I need to activate a virtualenv then start

相关标签:
1条回答
  • 2021-01-14 19:31

    1) Don't use old "init.d" method. Use something modern. If you have Ubuntu 15.04 and higher, you can use Systemd to create daemon that will be started automatically at startup. If you have for example Ubuntu older than 15.04 - use Upstart.

    For Systemd:

    Create unit file in /lib/systemd/system/you_service_name.service with the following content (as far as I can see your python script doesn't spawn new process while running, so Type should be simple. More info here):

    [Unit]
    Description=<your_service_name>
    After=network.target network-online.target
    
    [Service]
    Type=simple
    User=<required_user_name>
    Group=<required_group_name>
    Restart=always
    ExecStartPre=/bin/mkdir -p /var/run/<your_service_name>
    PIDFile=/var/run/<your_service_name>/service.pid
    ExecStart=/path/to/python_executable /path/to/your/script.py
    
    [Install]
    WantedBy=multi-user.target
    

    Save this file and reload systemd:

    sudo systemctl daemon-reload
    

    Then add your service to autostart:

    sudo systemctl enable you_service_name.service
    

    you should see that Systemd created required symlinks after enable action.

    Reboot and see if it's up and running (ps aux | grep python or sudo systemctl status you_service_name.service). If there is something weird - check Systemd journal:

    sudo journalctl -xe
    

    UPD:

    To launch your python script in desired virtualenv, just use this expression in your service unit file:

    ExecStart=/venv_home/path/to/python /venv_home/path/to/your/script.py
    

    2) You can also use crontab, but you need to specify full path for desired shell there, for example:

    @reboot /bin/bash /path/to/script.sh
    

    If you need additional help - just let me know here.

    0 讨论(0)
提交回复
热议问题