API 下载日志文件并转换 | Python
记录并下载.li 文件
要流式传输到文件(在单个脚本内记录和转换)而不是记录到文件,请参阅本文:
API 流和 stream_to_file | Python
首先,启动日志记录会话并下载文件。有关 API 的更多详细信息,请访问我们的 API 参考:
数据记录仪| API 参考download_file Python 数据记录器示例
# moku example: Basic Datalogger
# (c) 2025 Liquid Pty. Ltd.
import os
import time
from moku.instruments import Datalogger
# Connect to your Moku
i = Datalogger('192.168.###.###', force_connect=False)
try:
# Set-up the Datalogger
i.set_samplerate(100)
i.set_acquisition_mode(mode='Precision')
i.generate_waveform(channel=1, type='Sine', amplitude=1, frequency=10e3)
# Start a logging session
logFile = i.start_logging(duration=10)
# Track progress percentage of the data logging session
complete = False
while complete is False:
time.sleep(0.5)
progress = i.logging_progress()
complete = progress['complete']
if 'time_remaining' in progress:
print(f"Remaining time {progress['time_remaining']} seconds")
# Download the .li log from Moku
i.download(logFile['location'], logFile['file_name'],
os.path.join(os.getcwd(), logFile['file_name']))
print(f"Downloaded log file to local directory. {logFile['file_name']}")
except Exception as e:
print(f'Exception occurred: {e}')
finally:
# Close the connection to the Moku device
i.relinquish_ownership()
示例输出:
{'sample_rate': 100.0}
{'mode': 'Precision'}
{'amplitude': 1.0, 'frequency': 10000.0, 'offset': 0.0, 'phase': 0.0, 'type': 'Sine'}
...
Remaining time 0 seconds
Downloaded log file to local directory. MokuDataLoggerData_20250116_102402.li
Moku CLI 方法
确保您已安装 mokucli,您可以从实用程序页面下载它。
您可以从命令行转换为所需的文件类型:csv、npy、mat 或 hdf5。在本例中,我们将转换为 csv。将目录更改为文件所在的位置或使用完整文件路径:
C:\Users\user\Downloads>mokucli convert MokuDataLoggerData_20250116_102402.li --format=csv
[===========================================================================]
Done.
另一种方法是从脚本内部调用 mokucli,理想情况下,在这种用例中,将使用streaming
和stream_to_file
,请参阅此文章:
API 流和 stream_to_file | Python
从脚本内部调用 mokucli 不是最佳实践,但它可以作为一种选择:
import subprocess
sp = subprocess.run(f'mokucli convert --format=csv {logFile['file_name']}', capture_output=True, text=True)
print(sp.stdout)
file_name = logFile['file_name'][:-2] + 'csv'
LI 文件转换器方法
或者,你也可以使用 LI 文件转换器 GUI 转换文件,可以从Moku :应用程序访问或从实用程序页面下载

您可以选择文件类型,然后将文件拖放到转换器,或者使用“文件 | 打开文件”或“Ctrl/Cmd + O”从转换器打开文件

从文件加载数据
然后您可以使用转换后的文件来加载和分析数据。
import os
import csv
import numpy as np
import matplotlib.pyplot as plt
file_name = "MokuDataLoggerData_20250116_102402.csv"
channels = 2
print(file_name)
assert os.path.isfile(file_name), "Streaming failed, no file received"
data = {'time':[], 'ch1':[]}
with open(file_name, 'r') as f:
load = csv.reader(f)
file = np.array([[float(row[0])] + [float(row[i]) for i in range(1, channels+1)] for row in load if row[0][0] != '%'])
f.close()
data['time'] = file[:,0]
for i in range(1, channels+1):
data[f'ch{i}'] = file[:,i]
keys = data.keys()
for key in keys:
print(f"'{key}': {str(data[key][:3])[:-1]} ... {data[key][-1]}]")
fig = plt.figure(figsize=(10, 3))
for i in range(1, channels+1):
plt.plot(data['time'], data[f'ch{i}'], label=f'Channel {i}')
plt.title("Logged Data")
plt.grid(True)
plt.xlabel("Time (s)")
plt.ylabel("Voltage (V)")
plt.legend(loc=0)
plt.show()
示例输出:
MokuDataLoggerData_20250116_102402.csv
'time': [0. 0.01 0.02 ... 9.99]
'ch1': [0.00063297 0.00077466 0.00071688 ... 0.00067479823461]
'ch2': [0.01406568 0.01389566 0.014152 ... 0.014421103911]

Python 的其他文件类型转换和读取方法
这是文件类型转换的备忘单样式摘要以及如何在 Python 中读取它们,调整file_name
和channels
参数以匹配您的实验。
。垫
C:\Users\LItes\Downloads>mokucli convert MokuDataLoggerData_20250116_102402.li --format=mat
[===========================================================================]
Done.
import os
from scipy.io import loadmat
file_name = "MokuDataLoggerData_20250116_102402.mat"
channels = 2
print(file_name)
assert os.path.isfile(file_name), "Convert failed, no file received"
data = {'time':[], 'ch1':[]}
file = loadmat(file_name)
data['time'] = file['moku']['data'][0, 0][:,0]
for i in range(1, channels+1):
data[f'ch{i}'] = file['moku']['data'][0, 0][:,i]
keys = data.keys()
for key in keys:
print(f"'{key}': {str(data[key][:3])[:-1]} ... {data[key][-1]}]")
.npy
C:\Users\LItes\Downloads>mokucli convert MokuDataLoggerData_20250116_102402.li --format=npy
[===========================================================================]
Done.
import os
import numpy as np
file_name = "MokuDataLoggerData_20250116_102402.npy"
channels = 2
print(file_name)
assert os.path.isfile(file_name), "Convert failed, no file received"
data = {'time':[], 'ch1':[]}
load = np.load(file_name)
file = np.array([[load[i][0]] + [load[i][j] for j in range(1, channels+1)] for i in range(len(load))])
data['time'] = file[:,0]
for i in range(1, channels+1):
data[f'ch{i}'] = file[:,i]
keys = data.keys()
for key in keys:
print(f"'{key}': {str(data[key][:3])[:-1]} ... {data[key][-1]}]")
.hdf5
C:\Users\LItes\Downloads>mokucli convert MokuDataLoggerData_20250116_102402.li --format=hdf5
[===========================================================================]
Done.
import os
import numpy as np
import h5py
file_name = "MokuDataLoggerData_20250116_102402.hdf5"
channels = 2
print(file_name)
assert os.path.isfile(file_name), "Convert failed, no file received"
data = {'time':[], 'ch1':[]}
load = h5py.File(file_name, 'r')
file = np.array(list(load['moku']),dtype=np.dtype('float'+',float'*channels))
file.dtype.names=['time'] + [f'ch{i}' for i in range(1, channels+1)]
data['time'] = file['time']
for i in range(1, channels+1):
data[f'ch{i}'] = file[f'ch{i}']
keys = data.keys()
for key in keys:
print(f"'{key}': {str(data[key][:3])[:-1]} ... {data[key][-1]}]")