python - Return 在函数中捕获的值并将其添加到 csv 文件
python - Return a value captured in a function and add it to a csv file
我目前正在编写一段代码,但无论我尝试什么,我似乎都无法让它工作。
我想要做的是 return 一个函数的值,然后可以通过在代码的不同部分调用该函数来在函数外部访问该值。我希望在创建 csv 时将该值传递到代码区域。
这是包含我需要的值的函数。
def handleNotification(self, cHandle, data):
# Calculating the temperature in celsius and printing the value to the cmd
if cHandle == 24 and data[0] == '\x02':
temp_string = binascii.b2a_hex(data)
temp_val = temp_string[2:10]
temp_exp = temp_val[-2:]
temp_mes = temp_val [:-2]
temp_mes_swap = "".join(map(str.__add__, temp_mes[-2: :-2], temp_mes[-1: : -2]))
final_temp = int(temp_mes_swap, 16)*0.1
temp = format(final_temp)
#print temp
print ('Temperature: {0} Celsius'.format(final_temp))
return temp
如您所见,我正在尝试 return 函数的值 temp。然后我试图在下面的代码中调用这个函数和值 temp。我打算将 temp_reading 变量传递到 csv 中。
csv_data = retrieveData()
temp_reading = csv_data.handleNotification(24, temp)
当我执行代码时,出现以下错误 "float object has no attribute 'getitem'"。
临时变量在我的脚本顶部被定义为一个浮点数。
我是 python 的新手,所以很可能我遗漏了一些东西,但无论我怎么尝试,它都不起作用。感谢您的帮助:)
更新:我通过在 handleNotification 函数下创建另一个函数并将 temp 的值传递给它解决了这个问题。然后我能够调用新函数并将其分配给我可以在 csv 中使用的变量。
定义函数和传递参数的方式,
cHandle = 24
data = temp
行中
if cHandle == 24 and data[0] == '\x02':
data[0]
是错误的语法,因为 data
是一个浮点数(你提到 temp
是一个与 data
相同的浮点数)。
因此,错误。
我目前正在编写一段代码,但无论我尝试什么,我似乎都无法让它工作。
我想要做的是 return 一个函数的值,然后可以通过在代码的不同部分调用该函数来在函数外部访问该值。我希望在创建 csv 时将该值传递到代码区域。
这是包含我需要的值的函数。
def handleNotification(self, cHandle, data):
# Calculating the temperature in celsius and printing the value to the cmd
if cHandle == 24 and data[0] == '\x02':
temp_string = binascii.b2a_hex(data)
temp_val = temp_string[2:10]
temp_exp = temp_val[-2:]
temp_mes = temp_val [:-2]
temp_mes_swap = "".join(map(str.__add__, temp_mes[-2: :-2], temp_mes[-1: : -2]))
final_temp = int(temp_mes_swap, 16)*0.1
temp = format(final_temp)
#print temp
print ('Temperature: {0} Celsius'.format(final_temp))
return temp
如您所见,我正在尝试 return 函数的值 temp。然后我试图在下面的代码中调用这个函数和值 temp。我打算将 temp_reading 变量传递到 csv 中。
csv_data = retrieveData()
temp_reading = csv_data.handleNotification(24, temp)
当我执行代码时,出现以下错误 "float object has no attribute 'getitem'"。
临时变量在我的脚本顶部被定义为一个浮点数。
我是 python 的新手,所以很可能我遗漏了一些东西,但无论我怎么尝试,它都不起作用。感谢您的帮助:)
更新:我通过在 handleNotification 函数下创建另一个函数并将 temp 的值传递给它解决了这个问题。然后我能够调用新函数并将其分配给我可以在 csv 中使用的变量。
定义函数和传递参数的方式,
cHandle = 24
data = temp
行中
if cHandle == 24 and data[0] == '\x02':
data[0]
是错误的语法,因为 data
是一个浮点数(你提到 temp
是一个与 data
相同的浮点数)。
因此,错误。