To run a Python script as a service, you can use the built-in systemd service manager on most modern Linux distributions. Here are the steps you can follow:
STEP 1: Create a new service file: Create a new .service file in the /etc/systemd/system/ directory. You can choose any name for the service file, but it should have a .service extension. For example, let’s create a service file called myservice.service:
sudo nano /etc/systemd/system/myservice.service
STEP 2: Define the service: In the service file, define the service by setting its name, description, and the command to run the Python script. For example, here’s how you can define a simple service that runs a Python script:
[Unit]
Description=My Python Service
[Service]
User=your_username
WorkingDirectory=/path/to/your/python/script
ExecStart=/usr/bin/python3 /path/to/your/python/script/script.py
Restart=always
[Install]
WantedBy=multi-user.target
Note that you should replace your_username
and /path/to/your/python/script
with the appropriate values for your system.
STEP 3: Reload systemd and start the service: After creating the service file, you need to reload systemd and start the service. You can do this with the following commands:
sudo systemctl daemon-reload
sudo systemctl start myservice.service
STEP 4: Check the service status: You can check the status of the service with the following command:
sudo systemctl status myservice.service
This command will show you if the service is running, and if there are any errors or issues with it. If everything is working properly, the output should indicate that the service is active and running.
STEP 5: Finally Enable the service. To do this run this command:
sudo systemctl enable myservice.service
That’s it! Your Python script should now be running as a service, and it will automatically start whenever the system boots up.