Run Script in Foreground On Boot Raspberry Pi - python

I've a script to run on boot and I'd like to use the keyboard to interact with the script. I've successful set this up to run in crontab; however, the script runs in the background and I can't use the keyboard to interact with the script. Here's a simplified example of the script:
def write_to_txt(item_to_write):
with open("my_txt_file.txt", "a") as myfile:
myfile.write('\n'+str(item_to_write))
while True:
keys_to_enter = raw_input()
write_to_txt(keys_to_enter)
Please could someone point me in the right direction?

I found out how to run the script on boot and allow the keyboard to interact with the program. To the ~/.bashrc file, I appended:
sudo python /home/pi/example.py

If I understand correctly you want your program to attach its stdin to tty1? I.e. the terminal which you see on screen if you have a display hooked up - this is where by default keyboard input would end up if X windows is not installed or the tty is not switched with Ctrl+Alt+Fx?
Is moving the ownership of the background script process to the shell on tty1 an option? If so, the easiest may be to auto-login the Pi (or the user will need to login with the keyboard on startup). Then auto-start the program on tty1 so its stdin/stdout is tied to tty1.
To achieve the latter, I think you can put its invocation into one of the bash startup scripts, something like what is suggested here: https://www.raspberrypi.org/forums/viewtopic.php?f=29&t=7192

You can run a script in foreground at boot by adding a line to /etc/rc.local
This works in my experience, in particular if the Raspberry pi is configured to wait for network to be available when booting

Related

Embedded linux start python from crontab with terminal access and subprocess permissions

I have an embedded linux system that I need to run a python script whenever it boots. The python script needs to have a terminal interface so the user can interact and see outputs. The script also spawns another process to transfer large amounts of data over SPI, this was written in C.
I've managed to get the script to start on launch and have terminal access by adding
#reboot /usr/bin/screen -d -m python3 /scripts/my_script.py
to the crontab. I can then do "screen -r" and interact with the script. However if launched in this way the script fails to start the external SPI script. In python I launch the script with subprocess.Popen
proc=subprocess.Popen(["./spi_newpins,"-o","/media/SD/"+ latest_file"])
and this works perfectly whenever I manually launch the script, even within screen. Just not when it is launched by crontab. Does anyone have any ideas on how to get the spi subprocess to also work from crontab?
Fixed now, I had to add an absolute path to the spi_newpins function call
proc=subprocess.Popen(["/scripts/./spi_newpins","-o","/media/SD/"+ latest_file"])

Start terminal on Raspberry Pi using SSH

My question regards SSH on Raspberry Pi.
I am able to successfully ssh on to the Pi using the command:
sudo ssh pi#<ipaddress>
and then entering the password.
Let's say I have a Python script file on the Pi that I execute over SSH. Let's say the script reads:
import time
while True:
print('Hello')
time.sleep(1)
This will print 'Hello' every second whilst the terminal/command prompt window is still open (that is, the computer I am using to access the Pi is running and the SSH session remains open). If I close the connection, then the code will stop being executed on the Pi.
Is there a way I can use SSH to keep the code running on the Pi even when I close the window running SSH on the computer I am using to access the Pi? As in the Pi will keep printing 'Hello' even after I shut down my computer. Maybe by entering a command to open a terminal window on the Pi itself and running the script in that terminal window?
Is there a way this can be done?
Thanks
There are two options I can think of:
create a cron job. This method is usually used to execute scripts/programs repeatedly. The job is triggered by the cron program, so it doesn't matter whether or not you are connected to the Pi, as long as it runs. You just have to connect once and setup the job (typically using crontab -e).
use screen (on Wikipedia) or tmux (on Wikipedia). Those are called terminal multiplexers, and allow you to keep shells (and thus any script/program) running although you aren't connected. Note that, in this case, you will have to manually start your script each time, so this solution is well-suited to scripts that run for a long time but are not started too often.

How to run a python script on a remote server that it doesn't quit after I log off?

I've created a script for my school project that works with data. I'm quite new to working remotely on a server, so this might seem like a dumb question, but how do I execute my script named
stats.py
so that it continues executing even after I log off PuTTy? The script file is located on the server. It has to work with a lot of data, so I don't want to just try something and then few days later find out that it has exited right after I logged off.
Thank you for any help!
There are many ways you can run a python program after you disconnect from an SSH session.
1) Tmux or Screen
Tmux is a "terminal multiplexer" which enables a number of terminals to be accessed by a single one.
You start by sshing as you do, run it by typing tmux and executing it. Once you are done you can disconnect from putty and when you login back you can relog to the tmux session you left
Screen also does that you just type screen instead of tmux
2) nohup
"nohup is a POSIX command to ignore the HUP signal. The HUP signal is, by convention, the way a terminal warns dependent processes of logout."
You can run it by typing nohup <pythonprogram> &

Using SSH in Raspberry Pi to get Input?

I need to run Python scripts from SSH on my Raspberry Pi, while still being able to get input from a user on the Raspberry Pi via a USB keyboard emulator (card reader). I would normally be able to use raw_input for this, but if I run the Python script through SSH, it does not create a window and it will not be active so it will receive no input.
Is there any way to ensure a Python script will be active (the top window), even while using SSH to launch it? Or, is there another way to get user input without using raw_input, and works in the background (without an active window)?
Thanks in advance :)
PS: If I have to use other languages (like C) then invoke it in Python, this is fine, I will be able to do that.
I've solved it the best I can, with help from #Gaurav Dave
I now have a script which creates a new terminal window upon launch, using Popen from sys. The script looks like this...
from sys import executable
from subprocess import Popen, CREATE_NEW_CONSOLE
Popen([executable, 'window.py'], creationflags=CREATE_NEW_CONSOLE)
and window.py is simply a test script that prints some text and waits for a certain amount of time...
import time
print("Hello M8!")
time.sleep(5)
window.py will be the script that takes the input as that is the one that has the window.

Unix: Have Python script constantly running best practice?

I have a Python script which process data off of a HTTP data stream and I need this script to in theory be running at all times and forever unless I kill it off manually to update it and run it again.
I was wondering what the best practice to do this was on a Unix (Ubuntu in particular) so that even if Terminal is closed etc the script continues to run in the background unless the process or server are shut down?
Thanks
From your question you are implying that you are going to start the script from your terminal and not by any of Linux's startup script management methods like systemd or upstart or init.d scripts.
If you intend to start your script from terminal, and you want it to continue to run after you close your terminal, you need to do two things
1. Make it run in the background by appending '&' after your script.
2. When you close the terminal, the shell associated to it sends HUP signal to all the processes before it dying. To ignore the HUP signal and continue to run in the background you need to start your script with 'nohup'.
tl;dr
Run your script this way:
$ nohup python mypythonscript.py &
Adding your script to rc.local would work, but 'best practice' in my opinion would be to use Upstart. See this post:
Daemon vs Upstart for python script
It's an infinite loop. You can launch the script at startup and it will run forever until you kill the process itself or shut the computer down.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
while True:
print 'Hello'
time.sleep(2) # 2 second delay
I am not sure how "best practice" this is but you could do:
Add the program to:
/etc/rc.d/rc.local
This will have the program run at startup.
If you add an '&' to the end of the line it will be run in the background.
If you dont want to run the program manually (not at startup) you could switch to another tty by pressing ctrl + alt + f1, (this opens tty1 and will work with f1 - f6) then run the command. This terminal you do not have to have open in a window so you dont have to worry about it getting closed. To return to the desktop use ctrl + alt + f7.

Categories