When you run it from the console, the script reaches the end and exits.
Thonny, Mu and IDLE all keep your script running even though it's reached the end.
It's the #1 FAQ on the gpiozero docs: https://gpiozero.readthedocs.io/en/stable/faq.html#how-do-i-keep-my-script-running
You need to use signal.pause() from the standard library to keep the script ...
You could use cron for this. To schedule a cron job, you will use the crontab utility. Start by reading the man pages for cron and crontab. You could also search the Internet for information resources, and find something similar to this guide.
Once you have the gist (general idea) of this, try this from the command line of your RPi:
Anything run from rc.local will be run with root permissions so the use of sudo is redundant.
To run part of the script as another user use the su command. In particular use the form
su - pi -c "command you want to execute as the pi user"
What you try to do isn't possible this way with ssh. You have to understand how ssh works. It's abbreviation means secure shell and it opens a console (shell) on the connected pi2. It is a software terminal and keyboard doing just the same as a monitor and keyboard direct connected to pi2. With this you can't simply store content to a file on pi1 because ...
pigpio only provides PWM and servo pulses to the Pi GPIO on the expansion header. For the Pis with the 40 pin header this means (Broadcom) GPIO 0-27 inclusive.
In practical terms I doubt you will have much joy using a MCP23017 to provide servo signals. It will be extremely difficult to time synchronise accurately on/off pulses over the relatively slow I2C ...
So it turns out I had a lot of errors. This is what I ended up using. Aside from trying to check strings that didn't exist the string manipulation formatting was just wrong. I switched to just trimming the front and back of the string which contained'\r\n' and '~1 '
with serial.Serial('/dev/ttyAMA0', 115200, timeout=1) as ser:
If there is any error while running this on startup, you can’t see the error message. To check this, press ctrl+alt+F1. Here you can check the output of background processes. You can return to graphical display by ctrl+alt+F7.
This is the way you can ensure whether there is any error while running the code or not.
Now come to your solution, if there is any ...