OriginPro — OriginLab 自动化技能(Python API + LabTalk)
概要
本技能整合了两大 Origin 自动化工具:
- originpro — OriginLab 官方 Python 包,通过 Python 调用 Origin 的数据操作、图形绘制、分析等功能。
- LabTalk — Origin 原生脚本语言,可在 Origin 内部直接执行,也可通过
op.utils.lt_exec()从 Python 调用。
核心关系:originpro Python 包是对 Origin COM 接口的封装,底层大量操作最终通过 LabTalk 实现。Python 适合流程控制和数据处理,LabTalk 适合直接操作 Origin 对象属性和调用 X-Function。两者可以混合使用——在 Python 脚本中通过 lt_exec() 嵌入 LabTalk 语句,实现 Python API 尚未封装的功能。
- 官方文档:
- originpro: https://docs.originlab.com/originpro/index.html
- LabTalk: https://docs.originlab.com/labtalk/
- 包安装:
pip install originpro - 前提条件:需安装 Origin 软件(或 Origin Pro),Python 需能连接到 Origin 运行实例
何时使用
- 用 Python (originpro) 或 LabTalk 脚本自动化 Origin 数据导入、工作表变换、绘图、分析。
- 通过
op.utils.lt_exec(cmd)在 Python 中执行 LabTalk 命令(如 X-Function 调用、对象属性设置)。 - 调用 Origin X-Function(如
plotxy、impasc、wksheet、fitlr)。 - 读写 Origin 对象属性(
page、layer、wks、range等)。 - 定义 LabTalk 宏 或 用户自定义函数,实现流程控制。
- 调试 LabTalk 错误、token 限制问题或作用域问题。
- 使用 pandas/numpy 与 Origin 工作表/矩阵进行数据交换。
第一部分:originpro Python API
包结构
命名空间
| 命名空间 | 说明 | 关键内容 |
|----------|------|----------|
| originpro | 顶层 | 项目级函数:new_book, find_book, new_graph, open, save 等 |
| originpro.project | 项目操作 | new_book, find_book, find_graph, new_graph, open, save |
| originpro.utils | 工具函数 | lt_int, lt_exec, lt_tree_to_dict, ocolor, file_dialog 等 |
| originpro.graph | 图形操作 | Axis, GLayer, GPage, Plot 类;CopyPageRatio 函数 |
| originpro.worksheet | 数据表 | WBook, WSheet 类 |
| originpro.matrix | 矩阵 | MBook, MSheet 类 |
| originpro.analysis | 分析 | LinearFit, NLFit 类 |
| originpro.base | 基类 | BaseObject, BasePage, BaseLayer, DBook, DSheet, GObject, Label, Line |
| originpro.config | 配置 | APP 类 |
| originpro.dc | 数据连接 | Connector 类 |
| originpro.pe | 项目浏览器 | Folder 类 |
| originpro.notes | 备注 | Notes 类 |
| originpro.image | 图像 | IPage 类 |
| originpro.imp | 导入 | 导入相关函数 |
类继承层级
BaseObject
├── BasePage
│ ├── GPage (graph)
│ ├── WBook (worksheet)
│ ├── MBook (matrix)
│ ├── Notes (notes)
│ └── IPage (image)
├── BaseLayer
│ ├── GLayer (graph)
│ ├── WSheet (worksheet)
│ └── MSheet (matrix)
├── GObject (base)
│ ├── Label (base)
│ └── Line (base)
├── Axis (graph)
├── Plot (graph)
├── LinearFit (analysis)
├── NLFit (analysis)
├── APP (config)
├── Connector (dc)
├── Folder (pe)
├── DBook (base)
├── DSheet (base)
└── _LTTMPOUTSTR (utils)
类速查表
| 类 | 命名空间 | 说明 | 文档 | |----|----------|------|------| | WSheet | worksheet | 工作表操作(读写数据、列设置) | references/class_worksheet.md | | WBook | worksheet | 工作簿操作(管理多个工作表) | references/class_worksheet.md | | GPage | graph | 图形页面(保存导出、管理图层) | references/class_graph.md | | GLayer | graph | 图形图层(添加数据、坐标轴) | references/class_graph.md | | Plot | graph | 数据曲线(颜色、符号、样式) | references/class_graph.md | | Axis | graph | 坐标轴 | references/class_graph.md | | MBook | matrix | 矩阵簿 | references/class_matrix.md | | MSheet | matrix | 矩阵表 | references/class_matrix.md | | LinearFit | analysis | 线性拟合 | references/class_analysis.md | | NLFit | analysis | 非线性拟合 | references/class_analysis.md | | BaseObject | base | 所有对象基类 | references/class_base.md | | BasePage | base | 所有页面基类 | references/class_base.md | | BaseLayer | base | 所有图层基类 | references/class_base.md | | DBook | base | 数据簿基类 | references/class_base.md | | DSheet | base | 数据表基类 | references/class_base.md | | GObject | base | 图形对象基类 | references/class_base.md | | Label | base | 标签对象 | references/class_base.md | | Line | base | 线条对象 | references/class_base.md | | APP | config | 应用配置 | references/class_other.md | | Connector | dc | 数据连接器 | references/class_other.md | | Folder | pe | 项目浏览器文件夹 | references/class_other.md | | Notes | notes | 备注页 | references/class_other.md | | IPage | image | 图像页 | references/class_other.md |
快速入门
基本 workflow
import originpro as op
# 连接 Origin
op.new()
# 创建工作簿并写入数据
wks = op.new_book('w', 'MyData')[0]
wks.from_list([1, 2, 3, 4, 5], lname='X')
wks.from_list([2, 4, 6, 8, 10], lname='Y')
# 绘图
gp = op.new_graph(template='Line')[0]
gl = gp[0]
gl.add_plot(wks, col=1)
gl.rescale()
# 保存
gp.save_fig(r'C:\Users\me\graph.png', type='png')
生命周期与退出(推荐模板)
在脚本里正确管理 Origin 实例的生命周期非常重要:异常时也应调用
op.exit(),否则 Origin 进程可能残留。
import sys
import originpro as op
# ---- 异常保护:任何未捕获异常下也先退出 Origin ----
def origin_shutdown_exception_hook(exc_type, value, traceback):
op.exit()
sys.__excepthook__(exc_type, value, traceback)
if op and op.oext:
sys.excepthook = origin_shutdown_exception_hook
# ---- 控制 Origin 窗口可见性 ----
if op.oext:
op.set_show(True) # True=显示, False=隐藏
# ---- 业务代码 ----
# op.new()
# wks = op.new_book()[0]
# ...
# ---- 正常退出 ----
if op.oext:
op.exit()
关键说明:
op.oext为真表示当前通过 Origin Extender 连接到 Origin;脚本独立运行时通常为真。op.set_show(True/False)决定 Origin 窗口是否可见;隐藏窗口不会关闭进程,最终仍要op.exit()才能退出。- 如需保留 Origin 打开以便在 GUI 中查看,注释掉
op.exit()并去掉异常 hook。
常用 project 函数
| 函数 | 说明 |
|------|------|
| op.new() | 新建 Origin 项目 |
| op.open(path) | 打开 .opju 项目文件 |
| op.save(path) | 保存项目 |
| op.new_book(type, name) | 新建工作簿/矩阵簿,返回 (sheet, book) |
| op.find_book(name) | 按名称查找工作簿 |
| op.find_graph(name) | 按名称查找图形 |
| op.new_graph(template) | 新建图形,返回 (graphpage, layer) |
| op.new_sheet(type, lname) | 新建并返回第一个工作表 |
| op.find_sheet(type, ref) | 查找工作表 |
| op.load_book(fname) | 从文件加载工作簿/分析模板 |
| op.pages(type_) | 遍历项目中所有页面 |
常用 utils 函数
| 函数 | 说明 |
|------|------|
| op.utils.lt_exec(cmd) | 执行 LabTalk 命令(Python 调用 LabTalk 的桥梁) |
| op.utils.lt_int(cmd) | 执行 LabTalk 并返回整数 |
| op.utils.lt_float(cmd) | 执行 LabTalk 并返回浮点数 |
| op.utils.get_lt_str(vname) | 获取 LabTalk 字符串变量值 |
| op.utils.lt_tree_to_dict(name) | LabTalk 树转 Python 字典 |
| op.utils.ocolor(color) | 颜色值转换 |
| op.utils.path(type) | 获取 Origin 路径('u'=用户文件, 'e'=示例) |
| op.utils.file_dialog(type, title) | 文件选择对话框 |
| op.utils.evaluate_FDF(ffname, indepvars, params) | 评估 FDF 拟合函数 |
Python ↔ LabTalk 混合调用模式
originpro 的底层大量依赖 LabTalk,因此两种语言可以无缝混合:
import originpro as op
op.new()
wks = op.new_book()[0]
# Python 方式:写数据
wks.from_list(0, [1,2,3,4,5], lname='X', axis='X')
wks.from_list(1, [2,4,6,8,10], lname='Y', axis='Y')
# LabTalk 方式:调用 X-Function 绘图(Python API 未封装的功能)
op.utils.lt_exec('plotxy 2;')
# LabTalk 方式:设置对象属性
op.utils.lt_exec('layer.x.from = 0;')
op.utils.lt_exec('layer.x.to = 6;')
# 从 LabTalk 获取返回值
slope = op.utils.lt_float('fitLR.a') # 读取线性回归斜率
win_name = op.utils.get_lt_str('%H') # 读取当前窗口名
# 在对象上执行 LabTalk
wb = op.find_book()
wb.lt_exec('page.longname$ = "My Book"')
wks.lt_exec(r'expASC path:="c:\test\signal.csv";')
何时用 Python vs LabTalk:
- 用 Python:数据读写(pandas/numpy 互转)、流程控制、异常处理、与外部库集成。
- 用 LabTalk:X-Function 调用(plotxy、impasc、fitlr 等)、对象属性读写(page/layer/wks)、批量循环(doc -e)、Origin 内部特性(宏、字符串替换)。
- 混合用:Python 做主流程,
lt_exec()调用 LabTalk 完成 Python API 未覆盖的操作。
参考文件
Python API 参考
| 文件 | 内容 | |------|------| | references/namespaces_overview.md | 全部命名空间函数列表 | | references/class_hierarchy.md | 类继承层级完整树 | | references/class_worksheet.md | WBook / WSheet 完整方法文档 | | references/class_graph.md | GPage / GLayer / Plot / Axis 完整方法文档 | | references/class_matrix.md | MBook / MSheet 完整方法文档 | | references/class_base.md | 基类完整方法文档 | | references/class_analysis.md | LinearFit / NLFit 完整方法文档 | | references/class_other.md | APP / Connector / Folder / Notes / IPage 等类文档 | | references/functions_overview.md | 全部独立函数签名与说明 |
第二部分:LabTalk 脚本语言
LabTalk 是 Origin 的原生脚本语言,用于自动化数据导入、工作表操作、绘图、分析和报告生成。originpro Python 包底层大量调用 LabTalk,且可通过 op.utils.lt_exec() 从 Python 直接执行 LabTalk 语句。
核心语言快速参考
变量和作用域
- Numeric:
A = 3.5;— 名称不区分大小写。类型:double(默认)、int、const(不可变;自动保存到 orgvar.ogs)。 - String:
string greeting$ = "Hello";—$在声明时可选,赋值时必须。字符串寄存器%A…%Z为全局作用域。 - Dataset:
dataset aa = {1:0.2:10};= 临时 松散数据集(仅计算,不保存,不可绘图)。未声明赋值bb = {10:2:100};或create= 项目级松散数据集(可绘图)。 - StringArray:
StringArray sa; sa.Add("Boston"); sa.GetSize(); - Tree:
tree tr; tr.user.name$ = "dog"; tr.=;— 节点自动创建。 - GObject:
GObject myLine = [Graph1]1!line1;— 即使窗口非活动也可控制图形对象。 - 作用域: 未声明 double/string/dataset = Project 变量(保存在 OPJ 中);已声明 = Session(脚本窗口)或 Local(OGS/大括号);
@glob=1将局部提升为会话。局部覆盖会话覆盖项目。 - Range:
col(1) = data(1, 30);创建 30 行的列。赋值向量化:col(C) = col(A) + col(B);逐行运算。 - 命令不区分大小写,可缩写为两个字母(如
print→pr)。避免保留名:X,Y,Z,I,J,E,T、V1–V9等。
运算符
| 组 | 运算符 |
|----|--------|
| 算术 | + - * / ^ & \| (^ = 幂; &/\| 位运算) |
| 字符串连接 | + |
| 赋值 | = += -= *= /= ^= ++ -- |
| 关系 | > >= < <= == != |
| 逻辑 | && || |
| 条件 | ?: (三元) |
优先级:括号 → */ → +- → 关系 → ==/!= → || → && → ?:。乘法必须显式(2*X,不可 2X)。
字符串替换 %( )(关键)
四种替换类型:%A–%Z 字符串寄存器;%( ) 解析字符串变量/范围/单元格值;$( ) 数字→格式化字符串;%1–%5 宏/节参数。
%H= 活动窗口短名;%N= 长名;%C= 活动绘图/列;%X= 项目路径;%G= 项目名。%(var$)注入字符串变量值;%(page.name$)对象属性。%(Book1, 2)= 列名;%(Book1, 2, 3)= 单元格值;追加, W为显示格式。$(xx, .3)= 3 位小数,$(ii, ##)零填充,$(dDate, D1)长日期。- 陷阱:
type $(k)当 k<0 被解析为选项 → 用type "$(k)"。
aa$ = "Hello";
%K = "World";
dd$ = %(aa$) + " " + %K; // "Hello World"
string bk$ = %H; // 捕获活动窗口名
完整表格见 references/substitution-and-ranges.md。
流程控制
if (aa < 3) type "aa<3";
if (aa < 3 && aa < bb) { type "lower"; } else { type "not lower"; }
for (ii = 1; ii <= 10; ii++) { col(ii) = normal(30); }
loop (ii, 1, page.nlayers) { page.active = ii; } // 比 for 快
repeat 3 { newsheet; }
doc -e P { ... } // 遍历每个图形窗口
doc -e LB { ... } // 遍历项目中的每个工作表
doc -e G { ... } // 图形对象;%B = 当前对象名
switch (n) {
case 1: type "one"; break;
default: type "other";
}
循环内可用 break 和 continue。return 退出宏/函数。loop 比 for 快(无条件解析)。doc -e 循环可嵌套。
错误处理与稳健执行
{ ... }块是错误陷阱:块内出错会跳出到块后继续执行——脚本不会终止。@NOE = 0;静默错误输出。- 优先用
win -o Book1 { script }而非win -a Book1;+ 命令:在不切换活动窗口的情况下运行块内脚本(无时序问题)。 run.file(f.ogs)/run.section(f.ogs, Main, arg1, arg2)运行脚本文件。
宏
def MyMacro {
type "running";
// 大括号间最多 1140 tokens;超出时用宏拆分
}
MyMacro; // 按名执行
run -p MyMacro; // 替代执行方式
用户自定义函数
function double add(double x, double y) {
return x + y;
}
使用前必须声明;类型:double, int, string, range, tree, …。
X-Functions(现代 Origin API)
大多数分析/绘图操作是 X-Function,用 name arg:=value 调用(结尾一个分号,多行选项树也只一个)。任何 X-Function 支持 -h 查看帮助:impasc -h。
plotxy 3; // 快速绘制第 3 列
plotxy [Book1]Sheet1!(2,3:5) plot:=202; // 绘制 3-5 列 vs 第 2 列
impasc fname:="C:\data\a.dat"; // 导入 ASCII
wcellsel 1:end c:=ge v:=0.5; // 选择 >= 0.5 的单元格
关键 X-Functions: impasc, impCSV, impExcel, impfile, findfiles, plotxy, plotgroup, plotstack, plotxyz, plotm, wksheet, wsort, copydata, wtranspose, wxt, wcellsel, wcellcolor, wcellmask, discfreqs, rowstats, fitlr, fitPoly, fitMR, stats, nlbegin, nlfit, nlend, batchProcess, legendupdate, expGraph, dlgfile, w2m, m2w, vnormalize。
Ranges
range r1 = 1; // 活动表第 1 列
range r2 = [Book1]Sheet1!col(2);
range r3 = col(3)[1:50]; // 行 1-50 的子范围
r2 = r1; // 按范围赋值
完整指南见 references/substitution-and-ranges.md。
对象和属性
page— 活动窗口(.name$,.longname$,.active,.nlayers,.label$)。layer— 图形图层(.x.from,.x.to,.y.from,.maxpts,-g分组)。wks— 工作表(.ncols,.nrows,.col3.type,.c1/.c2/.r1/.r2)。wbk— 工作簿;book— 书籍操作。range,string,stringarray,tree,system.path.program$,system.math。
完整对象索引见 references/objects.md;命令索引见 references/commands.md;内置函数见 references/functions.md;完整示例脚本见 references/examples.md。
常用模式
// 新建工作簿 + 填充 + 快速绘图
newbook;
col(1) = data(1, 30);
col(2) = normal(30);
plotxy 2; // 绘制第 2 列 vs 第 1 列
// 导入后按组绘图
fn$ = system.path.program$ + "Samples\Statistics\body.dat";
newbook; impasc fn$;
wsort bycol:=3;
plotgroup iy:=(4,5) pgrp:=Col(3);
// 遍历所有工作表
doc -e LB {
type "Sheet: " %(wks.name$);
}
// 非线性拟合批处理(高斯峰)
findFiles ext:="T*.csv";
newbook sheet:=0;
for(int iFile = 1; iFile <= fname.GetNumTokens(CRLF); iFile++) {
string file$ = fname.GetToken(iFile, CRLF)$;
newsheet; impasc file$;
nlbegin iy:=2 func:=gaussamp nltree:=fit;
nlfit; nlend;
type "%(file$): center=$(fit.xc) height=$(fit.A) width=$(fit.w)";
}
常见陷阱
- 大括号 token 限制:
{ … }块最多 1140 字节;超出时移入宏。 - 作用域/活动窗口:许多命令作用于活动窗口——优先用
win -o <name> { ... }或显式[Book]Sheet!范围。 - 页面名引用(2023+):长名需引号
["My Book"],短名不可引用([Book1]、[%H])。 - 字符串 vs 数值比较:
if (%A == "")检查空;if ("%A" == 1)比较字面字符串。 - 乘法:必须显式(
2*X)。 - 保留变量名:不要重用
X, Y, Z, I, J, E, T, V1–V9。 - 循环中删除列/行:从右到左 / 从下到上迭代,否则索引会偏移。
input()式提示(getyesno/GetString)在无头运行中会挂起——用参数检查防护。
LabTalk 参考文件
| 文件 | 内容 |
|------|------|
| references/commands.md | 字母顺序命令参考及关键语法 |
| references/functions.md | 内置函数快速参考(数学、统计、字符串) |
| references/objects.md | 对象索引及常用属性/方法 |
| references/examples.md | 完整示例脚本(绘图、工作表、矩阵、报告表格式化) |
| references/substitution-and-ranges.md | 替换标记(%()、$()、@option)、完整范围标记、元数据/用户树 |
| references/automation-import-project.md | 导入、项目 & doc -e 循环、曲线拟合、批处理模板、Excel 互操作 |
第三部分:Python + LabTalk 混合实战模式
模式 1:Python 主流程 + LabTalk 补位
import originpro as op
op.new()
wks = op.new_book('w', 'Batch Data')[0]
# Python: 批量导入
fn = op.path('e') + r'Samples\Curve Fitting\Gaussian.dat'
wks.from_file(fn, False)
# LabTalk: 非线性拟合(Python API 的 NLFit 较繁琐时可直接用 LabTalk)
op.utils.lt_exec('nlbegin iy:=2 func:=Gauss nltree:=fit;')
op.utils.lt_exec('nlfit;')
op.utils.lt_exec('nlend;')
# Python: 读取结果
center = op.utils.lt_float('fit.xc')
amplitude = op.utils.lt_float('fit.A')
width = op.utils.lt_float('fit.w')
print(f"Center={center}, Amplitude={amplitude}, Width={width}")
模式 2:Python 数据处理 + LabTalk 绘图
import originpro as op
import numpy as np
op.new()
wks = op.new_book('w', 'Computed')[0]
# Python + numpy: 生成数据
x = np.linspace(0, 10, 100)
y = np.sin(x) * np.exp(-x/5)
wks.from_list(0, x.tolist(), lname='X', axis='X')
wks.from_list(1, y.tolist(), lname='Y', axis='Y')
# LabTalk: 绘图 + 格式化
op.utils.lt_exec('plotxy 2 plot:=200;') # 线图
op.utils.lt_exec('set %C -c 2;') # 红色
op.utils.lt_exec('set %C -w 2000;') # 线宽 2pt
op.utils.lt_exec('layer.x.from = 0; layer.x.to = 10;')
模式 3:LabTalk 批量循环 + Python 数据收集
import originpro as op
op.new()
# LabTalk: 批量导入 + 拟合,结果写入命令窗口
op.utils.lt_exec('''
string path$ = system.path.program$ + "Samples\\Batch Processing";
findFiles ext:="T*.csv";
newbook sheet:=0;
for(int iFile = 1; iFile <= fname.GetNumTokens(CRLF); iFile++) {
string file$ = fname.GetToken(iFile, CRLF)$;
newsheet; impasc file$;
nlbegin iy:=2 func:=gaussamp nltree:=myfit;
nlfit; nlend;
type "%(file$): center=$(myfit.xc)";
}
''')
# Python: 收集结果到 DataFrame
# (可将结果写入工作表,再用 to_df() 读出)
模式 4:在 originpro 对象上调用 LabTalk
import originpro as op
wks = op.new_sheet()
wks.from_list(0, [1,2,3,4,5], lname='X', axis='X')
wks.from_list(1, [2,4,6,8,10], lname='Y', axis='Y')
# 在工作表对象上执行 LabTalk
wks.lt_exec('wks.col2.lname$ = "Signal";') # 改列长名
wks.lt_exec('col(2) = col(2) * 2;') # 列数据乘 2
# 线性拟合
gp = op.new_graph()
gl = gp[0]
gl.add_plot(wks, col=1)
gl.rescale()
# LabTalk: 拟合并在图上生成报告
op.utils.lt_exec('fitlr iy:=(1,2) oy:=col(Fit);')
官方资源
- originpro 文档: https://docs.originlab.com/originpro/index.html
- originpro 类列表: https://docs.originlab.com/originpro/annotated.html
- originpro GitHub: https://github.com/originlib/originpro
- LabTalk 脚本指南: https://docs.originlab.com/labtalk/
- LabTalk 命令索引: https://docs.originlab.com/labtalk/ref/alphabetical-listing-of-commands/
- LabTalk 示例: https://docs.originlab.com/labtalk/examples/
微信扫一扫