John John - 25 days ago 10
Linux Question

How to run a python script with Raspberry Pi until we stop it manually

Currently I am working with both Raspberry Pi and Arduino at the moment. For Arduino in some cases, if we start running the script, then it will run until we stop them manually.

I am wondering if there is a way to do the same with a Raspberry Pi when using it with Python. For Raspberry Pi, when I use,

sudo python myprogramme.py


it runs my code just once and then it is stopped. Is there a way we can run the same code with command line several times until we stop them manually (For example, in MATLAB, we have to use crtl+z to stop the running script)?
(It may be possible by using a Loop but I am wondering if we can do that without using a Loop.) Hope my query makes sense.
My point of doing it is to send continuous information from a sensor to my system.

Answer

According to your comments ... when you hit CTRL+C the script gets the keyboard interrupt and you can gracefully shut down.

Your code:

import smbus
import time

while True:
    try:
        # Get I2C bus
        bus = smbus.SMBus(1)

        # BMP280 address, 0x76(118)
        # Read data back from 0x88(136), 24 bytes
        b1 = bus.read_i2c_block_data(0x76, 0x88, 24)
        # ... and the rest of your code. 
        # add a short sleep here at the end...
        sleep(0.1)
    except KeyboardInterrupt:
    # quit
        sys.exit()
Comments