Issue
as you can see i am writing the same code over and over again, how can i make an algorithm so to say, to iterate just a list of the parameters through the same line of code. Is that possible in this scenario or not. What i am doing is i am programming some values into a device through a serial connection. I want to automate it so yeah. This code works perfectly fine but i want to know how to write an algorithm to iterate through only the parameters. as yo can see only the .encode() value and the ft value is different in every line An example would be very helpful.
def write_par(self):
try:
reset_input = self.ser.reset_input_buffer()
reset_input
self.ser.write('\r\nft_seton ordoxo '.encode() + self.artikel_va.encode() + '\r\n'.encode())
reset_input
time.sleep(1.0)
self.ser.write('ft_seton hrdver '.encode() + self.HVVV.encode() + '\r\n'.encode())
reset_input
time.sleep(1.0)
self.ser.write('ft_seton hrdbrd '.encode() + self.HWB.encode() + '\r\n'.encode())
reset_input
time.sleep(1.0)
self.ser.write('ft_seton srll '.encode() + self.serien_nummer.encode() + '\r\n'.encode())
reset_input
time.sleep(1.0)
self.ser.write('ft_seton addr '.encode() + self.mac.encode() + '\r\n'.encode())
reset_input
time.sleep(1.0)
except Exception:
print('Device parameters were not written')
pass
Solution
Just use the Python for
functionality - it will always work as a "for each" and give you each element in a series.
You can either organize the names and attributes as tuples, or use the zip
call:
def write_par(self):
try:
reset_input = self.ser.reset_input_buffer # <- NB. no () in this line, otherwise it is called a single time
self.ser.write("\r\n")
for name, value in [
("ortodoxo", self.artikel_va),
("hrdver", self.HVVV),
("hrdbrd", self.HWB),
("srll", self.serien_nummer),
("addr", self.mac),
]:
self.ser.write(f'nft_seton {name} {value)\r\n'.encode()
reset_input()
time.sleep(1.0)
except Exception as error:
print(f'Device parameters were not written: at {name} we got {error}')
pass
As you can see, also: Python is not Basic, and there is no need to concatenate strings by opening and closing quotations and using the + operator. The "f-string" syntax will serve you well.
Another good practice is to print out what went wrong: you have that information while the program is running, and it is basically free to print it. If you print just "could not do it", that just means headaches that could have been avoided downstream.
Also, the first string to be printed out is different in your code: "nft_seto" vs "nt_seton" in your code. I assumed that was a typo. Otherwise, if you really need then to be different, just include this first string in the tuples, in the for loop and add another variable to carry it.
Answered By - jsbueno
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.