我需要檢查是否有函式呼叫,我知道它不是 txt 檔案,但是當我讀取一行并嘗試使用 type() 列印時,它顯示 str 并讓我正確列印所有檔案,但無論出于何種原因無法比較這些行,我不知道為什么,當我編譯時沒有顯示錯誤,檔案的第一行是,'#include <Arduino.h>'并且發現的 var 無論如何都是假的
import os
def BeforeBuild():
found = False
with open(r"\src\OTAWEBAP.cpp", "r") as f:
for line in f:
print (line)
if(line == '#include <Arduino.h>'):
found = True;
if(not found):
raise Exception("OtaIni function not found, you need to use it to preserve OTA functions in your new deploy")
else:
print('function OtaIni was found')
f.close()
BeforeBuild()
uj5u.com熱心網友回復:
嘗試更換
if(line == '#include <Arduino.h>'):
found = True;
和
if line.strip() == '#include <Arduino.h>':
found = True
strip() 函式洗掉行首和行尾的所有空格。
PS 盡量記住,在 Python 中,如果條件不需要在括號中并且行末尾不需要分號。否則每個人都會知道你是一個真正的 C 程式員。
uj5u.com熱心網友回復:
最后一個字符是\n如果您更改行。
所以這可能對你有用:-
import os
def BeforeBuild():
found = False
with open(r"\src\OTAWEBAP.cpp", "r") as f:
for line in f:
print (line)
if(line[:-1] == '#include <Arduino.h>'):
found = True;
if(not found):
raise Exception("OtaIni function not found, you need to use it to preserve OTA functions in your new deploy")
else:
print('function OtaIni was found')
f.close()
BeforeBuild()
uj5u.com熱心網友回復:
比較字串時應該小心。在這種情況下,導致此問題的空白字符。有很多無法看到但可能存在的空白字符。因此,處理此類檔案時的一個好習慣是洗掉這些空白字符。您可以使用strip()從字串的兩端洗掉空格字符。
import os
def BeforeBuild():
found = False
with open(r"\src\OTAWEBAP.cpp", "r") as f:
for line in f:
line = line.strip();
print (line)
if line == '#include <Arduino.h>':
found = True;
if not found:
raise Exception("OtaIni function not found, you need to use it to preserve OTA functions in your new deploy")
else:
print('function OtaIni was found')
f.close()
BeforeBuild()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/350589.html
