Ramirous
Ramirous

Reputation: 149

Python while loop not updating

I'm very new to Python.

I'm trying to display the current temperature from a sensor, which I get from a bash script. I use sed to replace the string in the python script (temp.py), which prints that string to an LCD Display.

Unfortunately, when I run temp.py, it only shows the temperature it has at the moment I run it, but it will not update, even though the lcd.py script is constantly changing (it only shows one temperature).

while True:
    lcd_string("Temp: 25.123 *C",LCD_LINE_1,1)
    time.sleep(1)

25.123 is changing constantly in temp.py, but not the different temperatures are not shown in the LCD

Is there any way to get it to update?

Upvotes: 0

Views: 393

Answers (4)

Hamlett
Hamlett

Reputation: 400

The .py file generates a bytecode to run. See the .pyc file beside your temp.py. So, once the script is running it won't load your change (the one made with sed command) in temp.py until you run it again.

I really suggest you another approach where you don't use an infinite loop but a single script that takes an argument every time it is executed and send the value to _lcd_string_ method.

Something like:

import sys

temp = sys.argv[1]
lcd_string("Temp: %s *C" % temp,LCD_LINE_1,1)

and instead of sed you can run:

python temp.py <your temperature>

Upvotes: 1

Jacky Wang
Jacky Wang

Reputation: 3520

A bad idea is to reload lcd.py every iteration, the newly value updated by sed will works after saving(the lcd.py file). The code as follows,

while True:
    reload(lcd)  # <-------- 
    lcd_string("Temp: 25.123 *C",LCD_LINE_1,1)
    time.sleep(1)

Note it is not recommended in practice.

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 114068

have your sed script constantly update a file called "label.txt" (you probably dont even need sed ... as an aside, why arent you just interfacing the sensor from python?)

then in your temp.py script

while True:
    lcd_string(open("label.txt").read(),LCD_LINE_1,1)
    time.sleep(1)

that is probably the easiest way to just make it work ... (See ned's answer as to why your original implementation did not work)

Upvotes: 2

Ned Batchelder
Ned Batchelder

Reputation: 375932

Changing the .py file on disk won't change the running program. The .py file is only read once, when the program starts. After that, the .py file isn't used again until the program is run again.

Upvotes: 5

Related Questions