US English (US)
JP Japanese
CN Chinese
KR Korean

Contact Us

If you still have questions or prefer to get help directly from an agent, please submit a request.
We’ll get back to you as soon as possible.

Please fill out the contact form below and we will reply as soon as possible.

  • Knowledge Base Home
  • Contact Us
Japanese
US English (US)
JP Japanese
CN Chinese
KR Korean
  • Home
  • Python API

API ストリーミングと stream_to_file | Python

Written by Nadia Hauser

Updated at April 9th, 2025

Contact Us

If you still have questions or prefer to get help directly from an agent, please submit a request.
We’ll get back to you as soon as possible.

Please fill out the contact form below and we will reply as soon as possible.

  • Moku:Lab
    Moku:Lab に関するよくある質問 Moku:Labロジックアナライザ/パターンジェネレータ Moku:Lab時間および周波数アナライザー Moku:Labスペクトラムアナライザー Moku:Lab PID コントローラ Moku:Labオシロスコープ Moku:Lab位相計 Moku:Labレーザーロックボックス Moku:Labデジタルフィルターボックス Moku:Lab任意波形ジェネレータ Moku:Lab波形ジェネレーター Moku:Lab周波数応答アナライザー Moku:Lab FIR フィルター ビルダー Moku:Labロックインアンプ Moku:Labデータロガー
  • Moku:Go
    Moku:Goに関するよくある質問 Moku:Goロックインアンプ Moku:Goロジックアナライザ & パターンジェネレータ Moku:Goオシロスコープ & 電圧計 Moku:Goスペクトラムアナライザー Moku:Go波形ジェネレータ Moku:Go時間・周波数アナライザー Moku:Goデジタルフィルターボックス Moku:Go FIR フィルター ビルダー Moku:Goレーザーロックボックス Moku:Go任意波形ジェネレータ Moku:Go周波数応答アナライザー Moku:Goデータロガー Moku:Go計 Moku:Go電源 Moku:Go
  • Moku:Pro
    Moku:Proに関するよくある質問 Moku:Pro波形発生器 Moku:Proタイム&周波数アナライザ Moku:Proロジックアナライザ/パターンジェネレーター Moku:Proレレーザーロックボックス Moku:Proロックインアンプ Moku:Proスペクトラムアナライザ Moku:Proデータロガー Moku:Pro任意波形発生器 Moku:Proマルチ機器モード Moku:Pro位相計 Moku:Pro FIRフィルタービルダー Moku:Pro PIDコントローラー Moku:Proオシロスコープ Moku:Pro周波数応答アナライザ Moku:Proデジタルフィルターボックス
  • Python API
  • MATLAB API
  • 任意波形発生器
  • データロガー
  • デジタルフィルターボックス
  • FIR フィルタ ビルダー
  • 周波数応答アナライザー
  • レーザーロックボックス
  • ロックインアンプ
  • オシロスコープ
  • 位相計
  • PIDコントローラー
  • スペクトラムアナライザー
  • 時間と周波数アナライザー
  • 波形発生器
  • ロジックアナライザ/パターンジェネレーター
  • マルチ機器モード
  • Mokuクラウドコンパイル
  • Mokuに関するよくある質問
  • LabVIEW API
+ More

ストリーミングオプション

APIの詳細については、 データロガー | API リファレンス 

ストリーミングstream_to_file Python のデータストリーミングの例

stream_to_file メソッド

これは、データをログに記録したいが、mokucli を使用して外部で変換したくない場合に便利です。このユースケースについては、 API ログ ファイルのダウンロードと変換 | Python を参照してください。これにより、ダウンロード中にファイルが変換され、ストリーミング セッションが完了すると分析できるようになります。

# moku example: Datalogger Stream to File
# (c) 2025 Liquid Pty. Ltd.
import os
import csv
import time
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
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 streaming session and stream to a file, include the file type in the
    # file name; csv, hdf5, npy, or mat
    i.start_streaming(duration=10)
    now = datetime.now().strftime("%Y%m%d_%H%M%S")
    file_name = f'MokuDataStreamingData_{now}.csv'
    i.stream_to_file(file_name)

    print(f"Streaming to file: {file_name}")
    print(i.get_stream_status()['status'])
    # Track progress percentage of the data streaming session
    status = 'RUNNING'
    while status == 'RUNNING':
        time.sleep(0.5)
        progress = i.get_stream_status()
        status = progress['status']

    # It may take a few moments for the file to appear in the system as accessible
    time.sleep(5)
    channels = 2
    print(file_name)
except Exception as e:
    i.relinquish_ownership()
    raise e
else:
    # Close the connection to the Moku device
    i.relinquish_ownership()

# Check for the file, then open the file and create data dictionary
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]

# Display the streamed data
keys = data.keys()
for key in keys:
    print(f"'{key}': {str(data[key][:3])[:-1]} ... {data[key][-1]}]")

# Plot the streamed data
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.xlim([data['time'][0], data['time'][-1]])
plt.title("Streamed to File Data")
plt.grid(True)
plt.xlabel("Time (s)")
plt.ylabel("Voltage (V)")
plt.legend(loc=0)
plt.show()

出力例:

Streaming to file: MokuDataStreamingData_20250116_165246.csv
RUNNING
MokuDataStreamingData_20250116_165246.csv
'time': [0.   0.01 0.02 ... 9.99]
'ch1': [0.00117748 0.00105914 0.00114431 ... 0.001142182695]
'ch2': [0.01485419 0.01477556 0.01476971 ... 0.01479722506]
stream_to_file データのプロット Python

他のファイルタイプへのストリーミングの場合:

file_name = f'MokuDataStreamingData_{now}.npy'
i.stream_to_file(file_name)
file_name = f'MokuDataStreamingData_{now}.hdf5'
i.stream_to_file(file_name)
file_name = f'MokuDataStreamingData_{now}.mat'
i.stream_to_file(file_name)

これらのファイル タイプからのデータを分析するには、この記事を参照してください。

Python のその他のファイルタイプの変換と読み取り方法

ストリーミング方式

この方法は、ストリーミング セッションが完了するのを待つのではなく、リアルタイムでデータを分析する場合に便利です。

# moku example: Datalogger Streaming
# (c) 2025 Liquid Pty. Ltd.
import os
import time
from moku.instruments import Datalogger
import matplotlib.pyplot as plt

# 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)

    # stream the data for 10 seconds..
    i.start_streaming(duration=10)

    # Set up the plotting parameters
    plt.ion()
    plt.show()
    plt.grid(visible=True)
    plt.ylim([-1, 1])
    plt.title("Streamed Data")
    plt.xlabel("Time (s)")
    plt.ylabel("Voltage (V)")
    line1, = plt.plot([])
    line2, = plt.plot([])
    plt.legend(['Channel 1', 'Channel 2'], loc=1)

    # Configure labels for axes
    ax = plt.gca()
    # This loops continuously updates the plot with new data
    while True:
        # get the chunk of streamed data
        data = i.get_stream_data()
        if data:
            plt.xlim([data['time'][0], data['time'][-1]])
            # Update the plot
            line1.set_ydata(data['ch1'])
            line1.set_xdata(data['time'])
            line2.set_ydata(data['ch2'])
            line2.set_xdata(data['time'])
            plt.pause(0.001)

except Exception as e:
    i.stop_streaming()
    print(e)
finally:
    i.relinquish_ownership()
ストリーミングデータのプロット Python

Was this article helpful?

Yes
No
Give feedback about this article

Related Articles

  • Python スペクトラム アナライザの「最大ホールド」機能
  • Pythonを使用して出力信号を観察しながら任意の波形を生成する
  • Mokuロックインアンプの復調信号の位相を変更する方法
  • ディープメモリモードでのデータ収集
  • 「pkg_resources という名前のモジュールがありません」というエラーを修正

Sitemap

  • Moku:Lab
  • Instruments
  • Software
  • Company
  • Support
  • Store
  • Terms & Conditions
  • Privacy Policy

Offices

United States
+1 (619) 332-6230
12526 High Bluff Dr
Suite 150
San Diego, CA 92130

Australia
+61 2 6171 9730
243 Northbourne Avenue
Suite 2
Lyneham, ACT 2602

Australia
+61 03 7073 3594
700 Swanston Street
Suite 5E, Level 5
Carlton, VIC 3053

Follow us

Youtube LinkedIn

官方微信

Contact us
© 2025 Liquid Instruments. All rights reserved.

Knowledge Base Software powered by Helpjuice

Definition by Author

0
0
Expand