I have faced a challenge that I could not solve. the code below generates data continuously. However, I want to put the condition to the value of "y". In other words, I want to sync this code with the time of the computer. I set the variable "current_hour".
But the problem is that I will have multiple conditions. When I first run the code it enters the correct condition and writes the desired value of the y. while the code is running I change the time of my local machine but value of the y DOES NOT change. When I stop the script and run it again at different times on the machine it enters the right condition. The purpose is that while the time of my computer changes, I want the condition (value of y in this case) to change (in real-time while code is running. I don't want to stop and rerun the code again). It sounds simple, and maybe it is. but I could not fix this. If it is not possible to sync the values with time while the script is running, then the project that I am doing doesn't make sense. I assume that when the first time I run the code it checks the conditions and enters that condition and keeps generating the value, in this case, I need to check every condition before generating each value.
import csv
import random
import time
import datetime
current_hour = datetime.datetime.now().hour
x_value = 0
y_value = 0
fieldnames = ["x_value", "y_value"]
while True:
with open('data.csv', 'a') as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
info = {
"x_value": x_value,
"y_value": y_value,
}
csv_writer.writerow(info)
print(x_value, y_value)
y_value = 30
x_value = 1
time.sleep(1)
CodePudding user response:
First of all, you never use current_hour after setting it, so I don't know what you mean by "first time it is correct".
Secondly, this is not how programming(at least procedural) works.
The only code that gets executed in loop is inside while loop. If you want to use your current time, you set it to query time inside loop.
It doesn't change otherwise. Variables are like boxes, once you put in box something, it doesn't change, unless you explicitly tell it to.
In this case, move current_hour=... line inside while loop, and actually refer to that variable, instead of using some mystical y_value variable which is set to 0 at start, and then to 30 in every run of the loop.