LinuxCNC: How to read current position in Python and log to CSV

Also see our post on how to just read the position especially if you don’t care about the CSV logging: LinuxCNC: How to find current position using Python

This script will log the position to CSV approximately every millisecond. The position will be logged in machine coordinates.

#!/usr/bin/env python2.7
import linuxcnc
import datetime
import time

stat = linuxcnc.stat()

with open("position-log.csv", "w") as outfile:
    while True:
       dt = datetime.datetime.now()
       stat.poll()
       x,y,z,a,b,c,u,v,w = stat.actual_position
       outfile.write("{},{:.4f},{:.4f},{:.4f}\n".format(dt.isoformat(), x, y, z))
       time.sleep(0.001)