pythonpandaslinuxservicesystemctl

Unable to import pandas on a linux service


I'm trying to create a simple service using Python and the service needs to import pandas for manipulating dataframes. I noticed that when I use "import pandas as pd", the service failed. I created a example to show the behavior.

Script main2.py (location: /home/silas/Desktop):

import pandas as pd
import logging
import time

while True:
    print('hello world')

    time.sleep(10)

my_service.service (location: /etc/systemd/system):

[Unit]
Description=Example
After=network.target

[Service]
ExecStart=/usr/bin/python3 /home/silas/Desktop/main2.py
Restart=always

[Install]
WantedBy=default.target

I opened the prompt and executed the commands:

systemctl start my_service.service
systemctl enable my_service.service
systemctl status my_service.service

I got the response telling me that my service is not running and failed:

 my_service.service - Example
      Loaded: loaded (/etc/systemd/system/my_service.service; enabled; vendor pr>
      Active: failed (Result: exit-code) since Tue 2023-08-08 19:49:53 -03; 1min>
 Main PID: 8776 (code=exited, status=1/FAILURE)
    CPU: 63ms

If I change the script to:

 import logging
 import time


 while True:

     print('hello world')

     time.sleep(10)

And execute the commands:

systemctl stop my_service.service
systemctl disable my_service.service
systemctl start my_service.service
systemctl enable my_service.service
systemctl status my_service.service

I got the response telling me that the service is running:

y_service.service - Example
     Loaded: loaded (/etc/systemd/system/my_service.service; enabled; vendor pr>
     Active: active (running) since Tue 2023-08-08 19:54:31 -03; 10s ago
   Main PID: 8952 (python3)
      Tasks: 1 (limit: 8994)
     Memory: 4.2M
        CPU: 26ms
     CGroup: /system.slice/my_service.service
             └─8952 /usr/bin/python3 /home/silas/Desktop/main2.py

Is possible to use pandas in this way? If so, what I'm doing wrong? If is not possible, how can I create a service using pandas?

Obs1: Pandas is installed in my machine, I'm not using virtual environment.

Obs2: If I execute the script with python3 main2.py, works normally with pandas.

Obs3: If I type which python3 in my prompt, shows the path configured in my_service.service.

enter image description here


Solution

  • I discovered that I can set the user in my .service file. I set my user in this format:

    my_service.service:

    [Unit]
    Description=Example
    After=network.target
    
    [Service]
    User=your_current_user
    ExecStart=/usr/bin/python3 /home/silas/Desktop/main2.py
    
    [Install]
    WantedBy=default.target
    

    Then I used the command:

    sudo systemctl restart my_service.service
    

    The service worked with pandas.