Run python script on startup linux

Autostart python scripts on boot with systemd

Recently I tried to run one of my Python projects on boot, and I was faced with the problem on how to do this elegantly on current Debian based Linux distros. After a bit of googling I found a quick and reliable way by utilizing a systemd service. Never mess again with strangle rc.local files or crontab @reboot solutions. With systemd services you can also reliably access logs and see the status of your process. This is especially useful for Python projects on things like a Raspberry Pi which you use headless and want to start your script as soon as it boots.

How To

Replace with a name descriptive of your project. Make it memorable because you probably have to remember it at some point.

    Find out the path to your python runtime with which

sudo systemctl --force --full edit .service 
[Unit] Description= After=network.target [Service] ExecStart= .py [Install] WantedBy=multi-user.target 
sudo systemctl daemon-reload 
sudo systemctl enable .service 

Variations

Time of start

The previous example assumes you want your script to start after the network interfaces were initialized and the OS is ready to use. You can change this behaviour by changing the values of the After= and WantedBy= parameters in the service file.

Virtual Environments

You can also start python scripts utilizing virtual environments this way by explicitly using the path to the python binary of your virtual environment like this:

ExecStart=/home//venv/bin/python .py 

Changing working directory

You can also change the working directory for your service before you start your script. This is especially useful if you reference relative paths in your code like machine learning models or asset folders. You can do this by adding a WorkingDirectory property to the service. Be aware that you still have to use absolute paths to reference your python executable and your script.

[Service] WorkingDirectory=/home/user/ ExecStart=/home//venv/bin/python .py 

Execute as user or group

Lastly you can execute your python script as specific Linux user and/or group e.g. as user “pi” if there are some specific permissions requiring this. For this to work you specify a user or group in the service part of the file. This is an example on how to do this for the user pi:

[Unit] Description= After=network.target [Service] ExecStart= .py User=pi Group=pi [Install] WantedBy=multi-user.target 

Managing the running script

Stop & Restart

You can stop your service by executing:

sudo systemctl stop .service 

The same goes for restarting it via:

sudo systemctl restart .service 

Status & Basic logs

You can check if your service is running or crashed by typing:

sudo systemctl status .service 

This will also show you the last few lines logged by your script (e.g. print statements).

Читайте также:  Change password in linux system

Disable autostart again

You can disable autostart for your new service at any time by typing:

sudo systemctl disable .service 

© 2023 David and Niklas Merz · Powered by Hugo & Coder.

Источник

How to Run Python Script at Startup in Ubuntu

The reputation of Python as a programming language speaks for itself. This programming language is attributed as general-purpose, high level, and interpreted.

Most Linux users are in love with the Python programming language due to its code readability which makes it easy to follow and master even for a beginner in the programming world.

Some advantages of Python Programming language are listed below:

  • Open-source and community development support.
  • Rich in third-party modules.
  • User-friendly data structures.
  • Dynamically typed programming language.
  • Interpreted language.
  • Highly efficient.
  • Portable and interactive.
  • Extensive libraries support.

The above-mentioned features make Python ideal for projects related to software development (desktop, web, gaming, scientific, image processing, and graphic design applications), operating systems, database access, prototyping, and language development.

This article will address the use of Python as a scripting language in an operating system environment (Ubuntu).

Prerequisites

Ensure you meet the following requirements:

  • You are a sudoer/root user on a Linux operating system distribution.
  • You can comfortably interact with the Linux command-line environment, interpret, and execute its associated commands.
  • You have the latest version of Python installed on Ubuntu.

Confirm that you have Python installed by running the command:

$ python3 --version Python 3.8.10

Running a Python Script at Startup in Ubuntu

The following steps will help us achieve the main objective of this article.

Step 1: Create Your Python Script

Create your Python script if it does not already exist. For this article guide purpose, we will create and use the following Python script.

Add the following Python script.

from os.path import expanduser import datetime file = open(expanduser("~") + '/Desktop/i_was_created.txt', 'w') file.write("This LinuxShellTips Tutorial Actually worked!\n" + str(datetime.datetime.now())) file.close()

Upon rebooting our Ubuntu system, the above Python script should be able to create a file called i_was_created.txt on the Ubuntu Desktop (Desktop). Inside this file, we should find the text This LinuxShellTips Tutorial Actually worked! together with the date and time of its creation.

Next, move the Python Script to a directory where it can be executed with root user privileges upon system restart. One such viable directory, in this case, is /bin.

Let us move the script using the mv command.

$ sudo mv python_test_code.py /bin

Now create a cron job scheduler that will periodically handle the execution of the above-created Python script (In this case during system startup).

Читайте также:  Линукс минт на ссд

At the bottom of this file, add the line:

@reboot python3 /bin/python_test_code.py &

Save and close the file and then confirm the creation of the cron job schedule:

Check Cron Job in Linux

The @reboot portion of the above line tells the cron job scheduler to execute the script at system startup. The & parameter informs the cron job scheduler to execute the Python script in the background so as not to interfere with normal system startup.

We are now ready to reboot our system

Let us check if our file was created:

$ cat ~/Desktop/i_was_created.txt && echo ''

Run Python Script at Ubuntu Startup

The existence of the above file confirms the Python script was successfully executed at the Ubuntu system startup.

Источник

Auto Start Python Script on Boot (Ubuntu 20.04, Systemd)

NOTE: Use After=network.service if you require network.

Create Bash Script

#!/bin/bash # cd /code/python/myapppython3 /code/python/myapp/run.py >> /code/logs/myapp.log 2>&1

Create Python Script

nano /code/python/myapp/run.py
import signalimport timeimport datetime is_shutdown = False def stop(sig, frame): print(f"SIGTERM at datetime.datetime.now()>") global is_shutdown is_shutdown = True def ignore(sig, frsma): print(f"SIGHUP at datetime.datetime.now()>") signal.signal(signal.SIGTERM, stop)signal.signal(signal.SIGHUP, ignore) print(f"START at datetime.datetime.now()>") while not is_shutdown: print('.', end='', flush=True) time.sleep(1) print(f"END at datetime.datetime.now()>")

Test Systemd

sudo chmod 744 /code/scripts/myapp.shsudo chmod 664 /etc/systemd/system/myapp.service
sudo systemctl daemon-reloadsudo systemctl enable myapp.service
sudo systemctl start myapp.service
sudo systemctl start status.service
sudo systemctl stop myapp.service

Restart server to test if the service started on reboot

Anaconda

Systemd is run as root by default. If you are using Anaconda (or maybe pyenv ), current user might not run the same python version/environment as root.

NOTE: I tried changing the user via Service.User , but it still uses the system default python interpreter

You can find the python interpreter path using which python or python -c «import sys; print(sys.executable)»

which pythonsudo which python

Edit the bash script to use the correct python interpreter

/opt/conda/bin/python3 /code/python/myapp/run.py >> /code/logs/myapp.log 2>&1

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

Travelopy — discover travel places in Malaysia, Singapore, Taiwan, Japan.

Источник

How to run python script at startup

I’m trying to make a Python script run as a service. It need to work and run automatically after a reboot. I have tried to copy it inside the init.d folder, But without any luck. Can anyone help?(if it demands a cronjob, i haven’t configured one before, so i would be glad if you could write how to do it) (Running Centos)

try putting the command in /etc/rc.local , make sure you use absolute path names, and don’t forget to background the process with & if the process runs continuously

3 Answers 3

@reboot /usr/bin/python /path/to/yourpythonscript 

save and quit,then your python script will automatically run after you reboot

There is no intrinsic reason why Python should be different from any other scripting language here.

Here is someone else using python in init.d: blog.scphillips.com/posts/2013/07/… In fact, that deals with a lot that I don’t deal with here, so I recommend just following that post.

Here is someone else using python in init.d: blog.scphillips.com/posts/2013/07/… In fact, that deals with a lot that I don’t deal with here, so I recommend just following that post.

For Ubuntu Variant:- open the /etc/rc.local file with:

add the following line just before the exit 0 line:

start-stop-daemon -b -S -x python /root/python/test.py 

Give absolute path of your command i.e

nohup /usr/bin/python2 /home/kamran/auto_run_py_script_1.py & 

The start-stop-daemon command creates a daemon to handle the execution of our program. The -b switch causes the program to be executed in the background. The -S switch tells the daemon to start our program. And the -x switch tells the daemon that our program is an executable.

Источник

Start a python script at boot on Ubuntu

I am new to python and have pretty basic knowledge of Linux. I need to start a script at boot time on a Ubuntu 14.04.3 server. The only thing is, the script is a monitoring tool and should be running all the time so I can’t just make a periodical cron call. I found this at first : running a python script with cron I have tried to add this in crontab :

@reboot python /path/to/script.py & 

but it doesn’t seems to work. I have also seen this : How to make a python script run like a service or daemon in linux The main answer is cron or a change in the python code. So my question is : Is there another way to run my script at boot and let it run «forever» without changing the code ? I assure you if I don’t want to change the code it’s not by lazyness but I will if it’s the only option. Other information (don’t know if it’s necessary), I am running Windows and have access to the server via PuTTY. The version of Python is 2.7 UPDATE Here is the cron log :

Nov 27 15:57:03 trustyovh cron[760]: (CRON) INFO (pidfile fd = 3) Nov 27 15:57:03 trustyovh cron[798]: (CRON) STARTUP (fork ok) Nov 27 15:57:03 trustyovh cron[798]: (CRON) INFO (Running @reboot jobs) Nov 27 15:57:03 trustyovh CRON[807]: (administrateur) CMD (/home/administrateur/scuMonitor/main.py &) Nov 27 15:57:03 trustyovh CRON[800]: (CRON) info (No MTA installed, discarding output) Nov 27 16:09:01 trustyovh CRON[1792]: (root) CMD ( [ -x /usr/lib/php5/maxlifetime ] && [ -x /usr/lib/php5/sessionclean ] && [ -d /var/lib/php5 ] && /usr/lib/php5/sessionclean /var/lib/php5 $(/usr/lib/php5/maxlifetime)) 
@reboot /home/administrateur/scuMonitor/main.py & 

UPDATE 2 Well, it was actually working with the cron set to reboot, but, my script didn’t put his log where I expected it to do (I wasn’t understanding how the path work on Linux). Thanks for all the answers everyone !

Источник

Оцените статью
Adblock
detector