How to run the code when system boots?

Options
bruce
bruce New Member Posts: 15
Hi,
I have connected a push button switch and LEDs (and one more peripheral) to the UP-board,
I have written a simple piece of code to turn on-off the LEDs using push button switch, but right now I also had connected keyboard, mouse and screen to the UP-Board, that means everytime I am opening the terminal and run the python code from there.

What I want is, when I turn on the UP-board and press the push button, the LEDs must work according to that button, without any kind of extra peripherals like keyboard, mouse, screen.

Let say I am going to put it in a small housing and then go anywhere. How to run the python script when the system boots ??

Need some guidance, Thanks.

Comments

  • WereCatf
    WereCatf New Member Posts: 201
    Options
    No. Anything you want to run in rc.local has to either have a full path specificed, or you need to set up the PATH-environment variable yourself first, as there is no such provided for you. This is to say, just simply calling script.py would not work, you need to either call /path/to/script.py or do export PATH=/path/to/:$PATH followed by script.py
  • Rick Baugh
    Rick Baugh New Member Posts: 7
    Options
    A more flexible way to run any kind of code is to install it as a systemd service. Then your service can be configured exactly _when_ in the bootup sequence to run your code, what to do if it fails or exits, and give you a quick and easy way to "dry run" your code w/o actually having to reboot your platform for each test.

    To do so, write a config file, call it <my_service_name>.service, that may look something like this:
    [Unit]
    Description=My really cool python app.
    After=syslog.target
    
    [Service]
    Type=oneshot
    RemainAfterExit=yes
    ExecStart=/usr/bin/python <absolute path of my script>.py
    SuccessExitStatus=1
    
    [Install]
    WantedBy=multi-user.target
    

    In ubilinux, you would put the file in the directory /lib/systemd/system, then use the following commands to install, enable, and/or test your service:

    systemctl daemon-reload // make systemd aware of your newly-minted (or edited) service file
    systemctl start <my_service_name> // test-run your service and see what happens
    systemctl stop <my_service_name> // oops, need to force-stop it (sends a SIGTERM then SIGKILL to app spec'd in ExecStart)
    systemctl enable <my_service_name> // enable my service to be run at bootup, but don't start it now
    systemctl disable <my_service_name> // don't run my service at bootup any more, but don't kill it now either
    journalctl -x --unit <my_service_name> // display any text my app may have sent to stdout/stderr while running (normally won't show)

    I find the journal feature a great aid in debugging my startup apps, something that an rc script won't easily show you.

    Good luck!