Managing sigrok-cli data with Python

From sigrok
Jump to: navigation, search

This page provides an example of how to incorporate sigrok-cli input commands and output data into a Python script. This allows for the easy setup of automated testing, data plotting and analysis. Note that sigrok-meter already serves this function for some devices, but does not currently support oscilloscopes.

Scripting sigrok-cli commands with the subprocess library in Python

As sigrok-cli uses a command-line interface the subprocess library can be used for sending and retrieving data. In this example, the following sigrok-cli command will return 100 samples at 1 MHz sample rate from a Hantek 6022BE oscilloscope as described in Using sigrok-cli with an oscilloscope.

$ sigrok-cli --driver hantek-6xxx --config samplerate=1m --samples 100

To send this command using subprocess and store the output data as a string we can use the following

 import subprocess
 import os
 
 sigrok_dir = 'C:\Program Files (x86)\sigrok\sigrok-cli' # sigrok-cli install dir
 sigrok_cmd = 'sigrok-cli --driver hantek-6xxx --config samplerate=1m --samples 100' # sigrok-cli command to be used
 
 os.chdir(sigrok_dir) # set working dir to sigrok_dir
 output = subprocess.run(sigrok_cmd, shell=True, check=True, capture_output=True, text=True) # open a new process, send the command and return the data
 raw_data = output.stdout

Printing the data returns the same information that would have been sent to the command prompt when working with sigrok directly.

 print(raw_data)

 CH1: 0.09 V
 CH1: 0.09 V
 CH1: 0.09 V
 CH1: 0.09 V
 CH1: 0.11 V
 CH1: 0.09 V
 CH1: 0.09 V
 CH1: 0.09 V
 ...

Alternatively, the data can be returned in the form of a CSV file (or similar) and imported into Python. See Using sigrok-cli with an oscilloscope for example commands.

See the single-phase-power-analyser project for an example use case.