Search code examples
pythoncron

how to properly run Python script with crontab on every system startup


I have a Python script that should open my Linux terminal, browser, file manager and text editor on system startup. I decided crontab is a suitable way to automatically run the script. Unfortunately, it doesn't went well, nothing happened when I reboot my laptop. So, I captured the output of the script to a file in order to get some clues. It seems my script is only partially executed. I use Debian 8 (Jessie), and here's my Python script:

#!/usr/bin/env python3

import subprocess
import webbrowser

def action():
    subprocess.call('gnome-terminal')
    subprocess.call('subl')
    subprocess.call(('xdg-open', '/home/fin/Documents/Learning'))
    webbrowser.open('https://reddit.com/r/python')

if __name__ == '__main__':
    action()

here's the entry in my crontab file:

@reboot python3 /home/fin/Labs/my-cheatcodes/src/dsktp_startup_script/dsktp_startup_script.py > capture_report.txt

Here's the content of capture_report.txt file (I trim several lines, since its too long, it only prints my folder structures. seems like it came from 'xdg-open' line on Python script):

Directory list of /home/fin/Documents/Learning/

                    Type       Format     Sort
                   [Tree    ] [Standard] [By Name] [Update]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
/  
... the rest of my dir stuctures goes here

I have no other clue what's possible going wrong here. I really appreciate your advice guys. thanks.


Solution

  • No, cron is not suitable for this. The cron daemon has no connection to your user's desktop session, which will not be running at system startup, anyway.

    My recommendation would be to hook into your desktop environment's login scripts, which are responsible for starting various desktop services for you when you log in, anyway, and easily extended with your own scripts.