johnnyrobot
Posts: 2
Joined: Wed May 22, 2019 8:40 pm

Python Script Spawned by Cron or Systemd doesn't write files..?

Fri May 24, 2019 5:04 pm

Hi all,

I've written a Raspberry Pi application (Ubuntu Mate) that's essentially a time-lapse camera. Every 5 seconds, it snaps an image and writes it to disk.

When I start the application manually from the terminal, it works as expected.

When I configure the script to execute automatically at startup, (using crontab or systemd - It needs to be executed as root) the script runs without any error, but no images are written to the disk.

At first I thought a permission issue, but the script is running as root... Any idea of what may be going on?

My script:

Code: Select all

import time
import cv2
import neopixel
import board
from pypylon import pylon

class Camera01:
    GiGe = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
    Light = neopixel.NeoPixel(board.D18, 16, bpp=4, auto_write=True)

count = 0

while True:
    # Open camera
    Camera01.GiGe.Open()

    # Turn on Light
    Camera01.Light.fill((255, 255, 255, 255))

    # Snap Image
    image = Camera01.GiGe.GrabOne(1000)

    # Convert image to OpenCV Array
    image = cv2.cvtColor(image.Array, cv2.COLOR_BAYER_BG2BGR)

    # Save image to disk
    cv2.imwrite('saved_images/image'+str(count)+'.png', image)

    # Turn off Light
    Camera01.Light.fill((0, 0, 0, 0))

    # Close camera
    Camera01.GiGe.Close()

    # Increment counter
    count = count + 1

    time.sleep(5)

Silverlock
Posts: 85
Joined: Wed Apr 10, 2013 3:51 am

Re: Python Script Spawned by Cron or Systemd doesn't write files..?

Fri May 24, 2019 5:47 pm

Code: Select all

    # Save image to disk
    cv2.imwrite('saved_images/image'+str(count)+'.png', image)
The file path that you're trying to write to is relative to the current working directory.

Ask yourself: what is the current working directory when you're running it as a cron job?

Either change your file path to an absolute path or put a cd command to the directory above the saved_images directory in your crontab entry before running your Python script. (i.e. cd /<insert your absolute path here>;python camera.py)
RPi3+external HDD/Raspbian Stretch

johnnyrobot
Posts: 2
Joined: Wed May 22, 2019 8:40 pm

Re: Python Script Spawned by Cron or Systemd doesn't write files..?

Fri May 24, 2019 6:53 pm

That was it! When I setup the application as a service, there is a "WorkingDirectory" assignment that I was missing. Once specified, it's working as it should. Thank you!

Code: Select all

[Unit]
Description=Time lapse camera application

[Service]
WorkingDirectory=/var/www/camera/
User=root
ExecStart=/usr/bin/python3 /var/www/camera/main.py
Restart=always

[Install]
WantedBy=multi-user.target

Return to “Python”