我想读取数据格式文件a_flag 所以我在这里有功能
def get_answer():
print("Creating r_flag data... ", end="")
r_flag = Flag(open("request.flg", "r+"))
print("Done")
print("Creating a_flag data... ", end="")
a_flag = Flag(open("answer.flg", "r+"))
print("Done")
print("Creating b_flag data... ", end="")
b_flag = Flag(open("busy.flg", "r+"))
print("Done")
# Wait until ready
print("Getting b_flag data... ", end="")
b_flag.get_data()
while b_flag.buffer[1] == 3:
b_flag.get_data()
print("Done")
# Request data
print("Set r_flag to REQUESTED... ", end="")
r_flag.set_stat([0, 0, 0, 0, 0, 0, 0, 0])
print("Done")
print("Now enter looping... ", end="")
while True:
print("Done")
print(" Getting a_flag data... ")
a_flag.get_data()
print(" got --> " + a_flag.buffer)
print(" Getting r_flag data... ")
r_flag.get_data()
print(" got --> " + r_flag.buffer)
if a_flag.is_answered() and r_flag.buffer:
print("Set r_flag to ACQUIRED... ", end="")
r_flag.set_stat([0, 2, 0, 0, 0, 0, 0, 0])
print("Done")
buffer = a_flag.buffer
del r_flag
del a_flag
del b_flag
print("Returning buffer")
return buffer
这是它的输出
Got a request: stat
Creating r_flag data... Done
Creating a_flag data... Done
Creating b_flag data... Done
Getting b_flag data... Done
Set r_flag to REQUESTED... Done
Now enter looping... Done
Getting a_flag data...
如您所见,它不会处理通过a_flag.get_data()的操作,该定义如下所示
class Flag():
def __init__(self, f):
self.flag_f = f
def __del__(self):
self.flag_f.close()
def get_data(self):
self.rewind()
self.buffer = self.flag_f.readline().split()
return self.buffer
def set_stat(self, data):
self.rewind()
for i in range(0, 8):
self.flag_f.write("{0} ".format(data[i], end=""))
def rewind(self):
self.flag_f.seek(0)
我完全不知道出了什么问题(请注意,它使用相同的函数正确地获得了b_flag数据形式)
answer.flg
0 1 0 0 0 0 0 0
busy.flg
1 4 0 0 0 0 0 0
request.flg
0 0 0 0 0 0 0 0
请忍受我的代码
答案 0 :(得分:0)
如果我运行您的代码,则会收到以下错误,该错误立即揭示了该问题:
TypeError Traceback (most recent call last)
<ipython-input-22-85d0a94e893a> in <module>
----> 1 get_answer()
<ipython-input-7-753bd9beab41> in get_answer()
26 print(" Getting a_flag data... ")
27 a_flag.get_data()
---> 28 print(" got --> " + a_flag.buffer)
29 print(" Getting r_flag data... ")
30 r_flag.get_data()
TypeError: must be str, not list
将语句更改为print(" got --> " + str(a_flag.buffer))
可以解决这个问题,即使它不是唯一的代码:您稍后必须对r_flag
做同样的事情,即使那样,您也会遇到您在is_answered
上使用Flag
的问题不存在。