我的問題很像這樣,但我使用的是極地。
環境:python 3.8,polars >=0.13.24
我有一個 CSV 檔案每 500 毫秒決議一次,但它可能會被另一個程式重置。當通過重新打開它重置時,極地將通過exceptions.NoDataError: empty csv并退出。
我試過的是將我的包裹read_csv在一個try-except塊中:
# These codes are in a function body
try:
result = pl.read_csv(result_file_name)
# do some transformation with the dataframe
return result
except:
# return an empty dataframe
return pl.DataFrame(
None, ["column", "names", "as", "it", "exist"]
)
但它仍然拋出例外。我對python不是很熟悉,所以不知道如何讓它落入except分支并回傳空資料框。
更新:(更詳細)
上面的代碼在一個名為 的函式parse_result中,用于將 CSV 檔案決議為polars.DataFrame. 它將在名為calculate的類的方法中呼叫UpdateData:
class UpdateData:
def __init__(
self, ax: Axes, trace_file_name: str, result_file_name: str, title: str
):
self.trace = parse_trace(trace_file_name)
self.result_file_name = result_file_name
self.ax = ax
self.lines = []
for i in range(2):
self.lines.append(self.ax.plot([], [], label=f"{i}")[0])
# plot parameters
# set ax parameters
# ...
def __call__(self, frame):
x, y = self.calculate()
self.lines[0].set_data(x, y[1])
self.lines[1].set_data(x, y[2])
return self.lines
def calculate(self):
result = parse_result(self.result_file_name)
# calculate x and y from result
# not important here
return x, y
# argpase code (not important)
if __name__ == "__main__":
args = parser.parse_args()
fig, ax = plt.subplots()
update_data = UpdateData(ax, args.trace, args.result, args.title)
anim = FuncAnimation(fig, update_data, interval=500)
plt.show()
我定義的函式parse_result非常像cbilot 的 answer,并且它單獨運行良好。
但是當我使用它UpdateData通過matplotlib繪制影片時,會出現錯誤:
File "/home/duskmoon/.local/lib/python3.8/site-packages/matplotlib/animation.py", line 907, in _start
self._init_draw()
File "/home/duskmoon/.local/lib/python3.8/site-packages/matplotlib/animation.py", line 1696, in _init_draw
self._drawn_artists = self._func(framedata, *self._args)
File "./liveshow.py", line 97, in __call__
x, y = self.calculate()
File "./liveshow.py", line 107, in calculate
result = parse_result(self.result_file_name)
File "./liveshow.py", line 72, in parse_result
self._draw_frame(frame_data)
File "/home/duskmoon/.local/lib/python3.8/site-packages/matplotlib/animation.py", line 1718, in _draw_frame
result = pl.read_csv(result_file_name)
File "/home/duskmoon/.local/lib/python3.8/site-packages/polars/io.py", line 333, in read_csv
df = DataFrame._read_csv(
File "/home/duskmoon/.local/lib/python3.8/site-packages/polars/internals/frame.py", line 587, in _read_csv
self._drawn_artists = self._func(framedata, *self._args)
File "./liveshow.py", line 97, in __call__
self._df = PyDataFrame.read_csv(
x, y = self.calculate()
exceptions.NoDataError: empty csv
File "./liveshow.py", line 107, in calculate
result = parse_result(self.result_file_name)
File "./liveshow.py", line 72, in parse_result
result = pl.read_csv(result_file_name)
File "/home/duskmoon/.local/lib/python3.8/site-packages/polars/io.py", line 333, in read_csv
df = DataFrame._read_csv(
File "/home/duskmoon/.local/lib/python3.8/site-packages/polars/internals/frame.py", line 587, in _read_csv
self._df = PyDataFrame.read_csv(
exceptions.NoDataError: empty csv
uj5u.com熱心網友回復:
你可以試試:
result = pl.read_csv(result_file_name, ignore_errors=true, columns=["column", "names", "as", "it", "exist"])
參考 - https://pola-rs.github.io/polars/py-polars/html/reference/api/polars.read_csv.html
uj5u.com熱心網友回復:
您可以檢查資料框的長度
result = pl.read_csv(result_file_name)
if len(result.index)==0:
quit()
#oranything you want to do
uj5u.com熱心網友回復:
錯誤看起來像這樣嗎?
SyntaxError: 'return' outside function
如果是這樣,則意味著您正在嘗試使用return不屬于函式定義的陳述句。
該return陳述句只能在函式定義中使用,例如:
def my_function(result_file_name):
try:
result = pl.read_csv(result_file_name)
# do some transformation with the dataframe
return result
except:
# return an empty dataframe
result= pl.DataFrame(
None, ["column", "names", "as", "it", "exist"]
)
return result
my_function("/tmp/tmp.csv")
>>> my_function("/tmp/tmp.csv")
shape: (0, 5)
┌────────┬───────┬─────┬─────┬───────┐
│ column ┆ names ┆ as ┆ it ┆ exist │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ f32 ┆ f32 ┆ f32 ┆ f32 ┆ f32 │
╞════════╪═══════╪═════╪═════╪═══════╡
└────────┴───────┴─────┴─────┴───────┘
但是,如果您不在函式定義中,則可以只分配result變數,而無需return宣告:
try:
result = pl.read_csv(result_file_name)
# do some transformation with the dataframe
except:
# return an empty dataframe
result= pl.DataFrame(
None, ["column", "names", "as", "it", "exist"]
)
print(result)
shape: (0, 5)
┌────────┬───────┬─────┬─────┬───────┐
│ column ┆ names ┆ as ┆ it ┆ exist │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ f32 ┆ f32 ┆ f32 ┆ f32 ┆ f32 │
╞════════╪═══════╪═════╪═════╪═══════╡
└────────┴───────┴─────┴─────┴───────┘
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/495889.html
