tia-python

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TIA Scripting Python V1.4.3

TIA Scripting Python V1.4.3

Library:
siemens_tia_scripting
(v1.4.3)
Use this skill for the Siemens-supplied Python wrapper around TIA Portal Openness. It is a reference-routed skill: do not select Python merely because a task mentions TIA Portal. If the implementation route is not already explicit, start with
tia-openness-roadmap
.
库:
siemens_tia_scripting
(v1.4.3)
本技能适用于西门子提供的、基于TIA Portal Openness的Python包装器。这是一个参考导向型技能:不要仅仅因为任务提到TIA Portal就选择Python。如果实现路线未明确说明,请从
tia-openness-roadmap
开始。

Evidence and qualification boundary

验证与资格边界

This package is aligned to the supplied Siemens V1.4.3 artifacts:
  • English manual
    109742322_TIA_Scripting_Python_DOC_V143_en.pdf
    , entry ID 109742322, dated 06/2026.
  • The
    siemens_tia_scripting.pyi
    stub bundled identically in the CPython 3.12, 3.13, and 3.14 wheels.
  • Siemens package metadata, changelog, and example workflows distributed with V1.4.3.
The manual and stub are the authority for public names and signatures. The changelog is the authority for version-to-version behavior notes. Static package inspection does not prove import success, installed products, licensing, live portal behavior, or project mutation on a particular engineering station.
本包与西门子提供的V1.4.3版本工件保持一致:
  • 英文手册
    109742322_TIA_Scripting_Python_DOC_V143_en.pdf
    ,条目ID为109742322,日期为2026年6月。
  • 在CPython 3.12、3.13和3.14安装包中统一捆绑的
    siemens_tia_scripting.pyi
    存根文件。
  • 随V1.4.3版本发布的西门子包元数据、更新日志和示例工作流。
手册和存根文件是公共名称与签名的权威依据,更新日志是版本间行为说明的权威依据。静态包检查无法证明导入成功、已安装产品、授权情况、Portal实时运行行为,或特定工程工作站上的项目变更情况。

Supported environment

支持的环境

  • Python 3.12.x, 3.13.x, or 3.14.x only, using the matching Windows x64 wheel.
  • The V1.4.3 manual states TIA Portal V15.1 or newer and TIA Portal Openness V15.1 or newer.
  • Siemens
    manifest.json
    lists V18-V21, while the delivered package contains adapter assemblies from V15.1 through V21.1. Treat this as mixed Siemens compatibility metadata: verify the exact installed Portal and update before promising runtime support.
  • The Windows user must belong to the
    Siemens TIA Openness
    group. The first connection can display the Siemens Openness security prompt.
  • 仅支持Python 3.12.x、3.13.x或3.14.x版本,需使用匹配的Windows x64安装包。
  • V1.4.3手册说明需TIA Portal V15.1或更高版本,以及TIA Portal Openness V15.1或更高版本。
  • Siemens的
    manifest.json
    列出了V18-V21版本,而交付的包包含V15.1至V21.1的适配器程序集。请将此视为西门子兼容性元数据的混合情况:在承诺运行时支持前,请验证已安装的Portal的确切版本并进行更新。
  • Windows用户必须属于
    Siemens TIA Openness
    用户组。首次连接时可能会显示西门子Openness安全提示。

Installation

安装

Do not install an unrelated package from PyPI. Use a wheel from the Siemens download or use the extracted-file import method.
请勿从PyPI安装无关包。请使用西门子下载的安装包,或使用提取文件导入法。

Siemens wheel

西门子安装包

Choose the wheel whose CPython tag matches the interpreter:
powershell
py -3.12 -m pip install .\install\siemens_tia_scripting-1.4.3-cp312-cp312-win_amd64.whl
py -3.13 -m pip install .\install\siemens_tia_scripting-1.4.3-cp313-cp313-win_amd64.whl
py -3.14 -m pip install .\install\siemens_tia_scripting-1.4.3-cp314-cp314-win_amd64.whl
Install only the wheel matching the interpreter. Siemens documents IntelliSense support through this package-install path with Pylance; other language servers are not qualified in the V1.4.3 manual.
选择与解释器CPython标签匹配的安装包:
powershell
py -3.12 -m pip install .\install\siemens_tia_scripting-1.4.3-cp312-cp312-win_amd64.whl
py -3.13 -m pip install .\install\siemens_tia_scripting-1.4.3-cp313-cp313-win_amd64.whl
py -3.14 -m pip install .\install\siemens_tia_scripting-1.4.3-cp314-cp314-win_amd64.whl
仅安装与解释器匹配的安装包。西门子文档说明通过此包安装路径,Pylance可提供智能提示支持;V1.4.3手册未认可其他语言服务器。

Extracted-file import

提取文件导入法

Set
TIA_SCRIPTING
to the extracted directory that contains
siemens_tia_scripting.pyd
and its Siemens adapter DLLs. Use the environment path only as a fallback when the wheel is not installed:
python
import importlib
import os
import sys
from pathlib import Path

try:
    ts = importlib.import_module("siemens_tia_scripting")
except ImportError as first_error:
    scripting_dir = os.environ.get("TIA_SCRIPTING")
    if not scripting_dir:
        raise RuntimeError(
            "Install the matching Siemens wheel or set TIA_SCRIPTING."
        ) from first_error

    resolved_dir = Path(scripting_dir).expanduser().resolve()
    if not (resolved_dir / "siemens_tia_scripting.pyd").is_file():
        raise RuntimeError(
            "TIA_SCRIPTING must contain siemens_tia_scripting.pyd."
        ) from first_error

    sys.path.insert(0, str(resolved_dir))
    ts = importlib.import_module("siemens_tia_scripting")
Do not copy the shipped examples' lifecycle and error handling verbatim. They are useful API-shape examples, but some V1.4.3 examples contain stale Python 3.12-only comments and do not reliably close or detach portal instances.
TIA_SCRIPTING
环境变量设置为包含
siemens_tia_scripting.pyd
及其西门子适配器DLL的提取目录。仅当未安装安装包时,才将环境路径作为备选方案:
python
import importlib
import os
import sys
from pathlib import Path

try:
    ts = importlib.import_module("siemens_tia_scripting")
except ImportError as first_error:
    scripting_dir = os.environ.get("TIA_SCRIPTING")
    if not scripting_dir:
        raise RuntimeError(
            "请安装匹配的西门子安装包或设置TIA_SCRIPTING环境变量。"
        ) from first_error

    resolved_dir = Path(scripting_dir).expanduser().resolve()
    if not (resolved_dir / "siemens_tia_scripting.pyd").is_file():
        raise RuntimeError(
            "TIA_SCRIPTING路径必须包含siemens_tia_scripting.pyd文件。"
        ) from first_error

    sys.path.insert(0, str(resolved_dir))
    ts = importlib.import_module("siemens_tia_scripting")
请勿直接复制附带示例的生命周期与错误处理代码。它们是有用的API形态示例,但部分V1.4.3示例包含仅适用于Python 3.12的过时注释,且无法可靠关闭或分离Portal实例。

Public object model

公共对象模型

text
siemens_tia_scripting
|-- Enums and 10 global functions
|-- ProductBundle -> Product
`-- Portal
    |-- Project
    |   |-- Device -> Module
    |   |-- Plc
    |   |   |-- DownloadConfig
    |   |   |-- ExecutionResult
    |   |   |-- ProgramBlock / SystemBlock / UserDataType
    |   |   |-- PlcTagTable -> PlcTag / UserConstant / SystemConstant
    |   |   |-- ExternalSource / ForceTable / WatchTable
    |   |   |-- TechnologyObject / SafetyAdministration
    |   |   `-- SoftwareUnit -> NamedValueType and PLC data objects
    |   |-- Hmi
    |   |   |-- HmiTagTable / HmiTag / HmiScreen / HmiScript
    |   |   `-- HmiAlarm / HmiAlarmClass / HmiConnection / HmiCycle
    |   |       / HmiGraphicList / HmiTextList
    |   |-- ProjectLibrary -> MasterCopy / LibraryType -> LibraryTypeVersion
    |   `-- ApplicationTest / RuleSet / SystemTest
    |-- ProjectServer
    `-- GlobalLibraryInfo / GlobalLibrary
        `-- LibraryType -> LibraryTypeVersion
The V1.4.3 stub contains 10 global functions and 45 public classes. Load the domain reference files below instead of expanding this entrypoint with every method.
text
siemens_tia_scripting
|-- 枚举类型与10个全局函数
|-- ProductBundle -> Product
`-- Portal
    |-- Project
    |   |-- Device -> Module
    |   |-- Plc
    |   |   |-- DownloadConfig
    |   |   |-- ExecutionResult
    |   |   |-- ProgramBlock / SystemBlock / UserDataType
    |   |   |-- PlcTagTable -> PlcTag / UserConstant / SystemConstant
    |   |   |-- ExternalSource / ForceTable / WatchTable
    |   |   |-- TechnologyObject / SafetyAdministration
    |   |   `-- SoftwareUnit -> NamedValueType和PLC数据对象
    |   |-- Hmi
    |   |   |-- HmiTagTable / HmiTag / HmiScreen / HmiScript
    |   |   `-- HmiAlarm / HmiAlarmClass / HmiConnection / HmiCycle
    |   |       / HmiGraphicList / HmiTextList
    |   |-- ProjectLibrary -> MasterCopy / LibraryType -> LibraryTypeVersion
    |   `-- ApplicationTest / RuleSet / SystemTest
    |-- ProjectServer
    `-- GlobalLibraryInfo / GlobalLibrary
        `-- LibraryType -> LibraryTypeVersion
V1.4.3存根文件包含10个全局函数和45个公共类。请加载下方的领域参考文件,而非在此入口点展开所有方法。

Cross-cutting contracts

跨领域约定

Properties

属性

The V1.4.3 manual and stub annotate
get_property(name: str) -> str
and say non-string values are converted to strings where possible. The V1.3.0 changelog instead says property values are returned as their original boolean or numeric type. Because the supplied authorities conflict, generated code must not assume one representation:
python
value = obj.get_property(name="CreationDate")
if isinstance(value, bool):
    normalized = value
elif isinstance(value, str):
    normalized = value.strip()
else:
    normalized = value
set_property(name: str, value: str) -> int
still requires a string value. Pass booleans, numbers, and enums as their documented string representation.
V1.4.3手册和存根文件标注了
get_property(name: str) -> str
,并说明非字符串值会尽可能转换为字符串。而V1.3.0更新日志则说明属性值会以原始布尔值或数值类型返回。由于官方资料存在冲突,生成代码不得假设某一种返回格式:
python
value = obj.get_property(name="CreationDate")
if isinstance(value, bool):
    normalized = value
elif isinstance(value, str):
    normalized = value.strip()
else:
    normalized = value
set_property(name: str, value: str) -> int
仍要求传入字符串值。请将布尔值、数字和枚举类型转换为文档规定的字符串表示形式后传入。

Export and import

导出与导入

The common V1.4.3 export signature is:
python
obj.export(
    target_directory_path=r"C:\Engineering\export",
    export_options=ts.Enums.GeneralExportOptions.WithDefaults,
    export_format=ts.Enums.GeneralExportFormats.SimaticML,
    keep_folder_structure=True,
)
Most V1.4.3 import methods accept
import_options: Optional[Enums.GeneralImportOptions]
. PLC/HMI bulk imports use an import root directory; explicitly named project-text, CFC, CAx, global-screen, screen-overview, configuration, and password-policy operations use file paths. Check the domain reference before choosing a path shape.
V1.4.3通用导出签名如下:
python
obj.export(
    target_directory_path=r"C:\Engineering\export",
    export_options=ts.Enums.GeneralExportOptions.WithDefaults,
    export_format=ts.Enums.GeneralExportFormats.SimaticML,
    keep_folder_structure=True,
)
大多数V1.4.3导入方法接受
import_options: Optional[Enums.GeneralImportOptions]
参数。PLC/HMI批量导入使用导入根目录;明确指定的项目文本、CFC、CAx、全局画面、画面概览、配置和密码策略操作使用文件路径。选择路径形式前,请查阅领域参考文档。

Compile and execution results

编译与执行结果

  • Device.compile()
    ,
    Module.compile()
    , PLC compile methods, block/UDT/ technology-object compile methods, and
    SoftwareUnit.compile()
    return
    ExecutionResult
    .
  • ExecutionResult
    exposes
    get_result_state()
    ,
    get_all_messages()
    ,
    get_warnings()
    ,
    get_errors()
    ,
    get_information()
    , and
    print_result()
    .
  • Hmi.compile_hardware()
    and
    Hmi.compile_software()
    remain the exception: they return
    True
    when errors exist and
    False
    when no errors exist.
  • The V1.3.0 changelog calls its breaking result change an "ExecutionReport" object, but the delivered V1.4.3 manual and stub expose the callable class as
    ExecutionResult
    . Use
    ExecutionResult
    in code.
Do not discard result objects or rely only on console logging:
python
result = plc.compile_software()
errors = result.get_errors()
if errors:
    raise RuntimeError("PLC compile failed: " + " | ".join(errors))
  • Device.compile()
    Module.compile()
    、PLC编译方法、块/UDT/技术对象编译方法以及
    SoftwareUnit.compile()
    均返回
    ExecutionResult
  • ExecutionResult
    提供
    get_result_state()
    get_all_messages()
    get_warnings()
    get_errors()
    get_information()
    print_result()
    方法。
  • Hmi.compile_hardware()
    Hmi.compile_software()
    是例外情况:当存在错误时返回
    True
    ,无错误时返回
    False
  • V1.3.0更新日志称其突破性结果变更为
    ExecutionReport
    对象,但交付的V1.4.3手册和存根文件将可调用类暴露为
    ExecutionResult
    。请在代码中使用
    ExecutionResult
请勿丢弃结果对象或仅依赖控制台日志:
python
result = plc.compile_software()
errors = result.get_errors()
if errors:
    raise RuntimeError("PLC编译失败:" + " | ".join(errors))

Exact V1.4.3 enums

V1.4.3精确枚举类型

text
PortalMode: WithGraphicalUserInterface=0, WithoutGraphicalUserInterface=1,
            AnyUserInterface=2
UmacUserMode: Project=0, Global=1
GeneralExportFormats: SimaticML=0, ExternalSource=1, SimaticSD=2
GeneralExportOptions: WithDefaults=0, Nan=1, WithReadOnly=2
LibraryCleanUpMode: PreserveDefaultVersionOfUnusedTypes=0, DeleteUnusedTypes=1
LibraryExportOptions: Nan=0, WithLibraryVersionInfoFile=1,
                      OnlyLibraryVersionInfoFile=2
LibraryHarmonizeOptions: HarmonizePathsAndNames=0, HarmonizePaths=1,
                         HarmonizeNames=2
LibraryDependenciesMode: DoNotAutomaticallyCreateOrReleaseDependencies=0,
                         AutomaticallyCreateOrReleaseDependenciesIfRequired=1
GeneralDownloadOptions: Hardware=0, Software=1, HardwareAndSoftware=2,
                        SoftwareOnlyChanges=3,
                        HardwareAndSoftwareOnlyChanges=4
TestSuiteTestCaseImportOptions: Nan=0, IgnoreInvalidObject=1
TestSuiteRuleSetImportOptions: Nan=0, IgnorePropertyErrors=1,
                               IgnoreMissingAttributes=2, SkipInvalidObjects=3,
                               IgnoreErrorsAndAttributes=4
GeneralImportOptions: Nan=0, Override=1, SkipInactiveCultures=2,
                      ActivateInactiveCultures=3
ConsoleLogLevel: All=0, Info=1, Warning=2, Error=3
text
PortalMode: WithGraphicalUserInterface=0, WithoutGraphicalUserInterface=1,
            AnyUserInterface=2
UmacUserMode: Project=0, Global=1
GeneralExportFormats: SimaticML=0, ExternalSource=1, SimaticSD=2
GeneralExportOptions: WithDefaults=0, Nan=1, WithReadOnly=2
LibraryCleanUpMode: PreserveDefaultVersionOfUnusedTypes=0, DeleteUnusedTypes=1
LibraryExportOptions: Nan=0, WithLibraryVersionInfoFile=1,
                      OnlyLibraryVersionInfoFile=2
LibraryHarmonizeOptions: HarmonizePathsAndNames=0, HarmonizePaths=1,
                         HarmonizeNames=2
LibraryDependenciesMode: DoNotAutomaticallyCreateOrReleaseDependencies=0,
                         AutomaticallyCreateOrReleaseDependenciesIfRequired=1
GeneralDownloadOptions: Hardware=0, Software=1, HardwareAndSoftware=2,
                        SoftwareOnlyChanges=3,
                        HardwareAndSoftwareOnlyChanges=4
TestSuiteTestCaseImportOptions: Nan=0, IgnoreInvalidObject=1
TestSuiteRuleSetImportOptions: Nan=0, IgnorePropertyErrors=1,
                               IgnoreMissingAttributes=2, SkipInvalidObjects=3,
                               IgnoreErrorsAndAttributes=4
GeneralImportOptions: Nan=0, Override=1, SkipInactiveCultures=2,
                      ActivateInactiveCultures=3
ConsoleLogLevel: All=0, Info=1, Warning=2, Error=3

Logging

日志

Configure file/console logging before opening or attaching TIA Portal, and set the console level separately when required:
python
ts.set_logging(path=r"C:\Engineering\logs\tia-scripting.log", console=True)
ts.set_log_level(log_level=ts.Enums.ConsoleLogLevel.Info)
在打开或连接TIA Portal之前配置文件/控制台日志,并根据需要单独设置控制台日志级别:
python
ts.set_logging(path=r"C:\Engineering\logs\tia-scripting.log", console=True)
ts.set_log_level(log_level=ts.Enums.ConsoleLogLevel.Info)

Reference routing

参考导向

Load every reference needed by a cross-domain workflow before generating code.
ReferenceLoad for
skills/tia-python/references/global_portal.md
Global functions, portal lifecycle, credentials, products, devices, and modules
skills/tia-python/references/plc.md
PLC online/download, compilation, imports/exports, CFC, Safety, software units, and PLC data objects
skills/tia-python/references/hmi.md
Generic wrapper HMI discovery, compile, import/export, and HMI object classes
skills/tia-python/references/library.md
Global/project libraries, master copies, types, and versions
skills/tia-python/references/project.md
Project lifecycle, transactions, project texts, CAx, project servers, and Test Suite
生成代码前,请加载跨领域工作流所需的所有参考文档。
参考文档适用场景
skills/tia-python/references/global_portal.md
全局函数、Portal生命周期、凭据、产品、设备和模块
skills/tia-python/references/plc.md
PLC在线/下载、编译、导入/导出、CFC、安全功能、软件单元和PLC数据对象
skills/tia-python/references/hmi.md
通用包装器HMI发现、编译、导入/导出和HMI对象类
skills/tia-python/references/library.md
全局/项目库、主副本、类型和版本
skills/tia-python/references/project.md
项目生命周期、事务、项目文本、CAx、项目服务器和测试套件

Destructive-operation safety and authority rules

破坏性操作安全与权限规则

These rules are mandatory for generated TIA Scripting Python:
  1. Treat project/library creation, import, property writes, master-copy instantiation, protection changes,
    delete()
    and other deletion calls, save, archive, compile-triggered generation, and hardware upgrade as mutations. Require explicit mutation authorization and exact selectors.
  2. Require explicit live-operation authorization before
    go_online()
    ,
    go_offline()
    ,
    download()
    , online comparison, online fingerprints, or any operation that communicates with a PLC. Confirm the exact target using
    pc_interface_type
    ,
    pc_interface_name
    , and
    target_interface
    ; never infer a target from the first device or first accessible interface.
  3. Inspect every
    ExecutionResult
    and stop on errors. For HMI compile calls, remember that
    True
    means errors exist.
  4. After generated block, tag, hardware, or HMI changes, run or request a
    compile_check
    through MCP. Do not present the project change as deployable until that check passes.
  5. Do not save, archive, commit a server session, close a portal, delete, or overwrite existing content unless that exact action was authorized.
  6. Use
    project.start_transaction()
    /
    project.end_transaction()
    only around already authorized mutations supported by the transaction, and roll back on every exception path:
python
transaction_open = False
try:
    project.start_transaction(
        undo_text="Authorized TIA change",
        dialog_text="Applying reviewed Python changes",
    )
    transaction_open = True
    # Perform only the already authorized mutation here.
    project.end_transaction(rollback=False)
    transaction_open = False
except Exception:
    if transaction_open:
        project.end_transaction(rollback=True)
    raise
  1. A transaction does not make an unsupported operation safe. If the wrapper or target object cannot provide the required exclusive-access, rollback, exact selection, or result evidence, route the task to C# Openness or MCP through a guarded workflow.
  2. Do not hardcode, print, or commit UMAC, Safety, know-how, module-access, or PLC master-secret credentials. Read them from the user's approved secret mechanism and pass them only to the exact authorized call.
  3. When this script attached to a user-owned portal, use
    portal.detach()
    in cleanup. Call
    portal.close_portal()
    only for an instance the script owns and only after the project disposition has been explicitly decided.
以下规则对生成的TIA Scripting Python代码具有强制性:
  1. 将项目/库创建、导入、属性写入、主副本实例化、保护设置变更、
    delete()
    及其他删除调用、保存、归档、编译触发的生成操作和硬件升级视为变更操作。要求明确的变更授权和精确的选择器。
  2. 在执行
    go_online()
    go_offline()
    download()
    、在线比较、在线指纹识别或任何与PLC通信的操作前,要求明确的实时操作授权。使用
    pc_interface_type
    pc_interface_name
    target_interface
    确认精确目标;绝不能从第一个设备或第一个可访问接口推断目标。
  3. 检查每个
    ExecutionResult
    并在出现错误时停止。对于HMI编译调用,请记住
    True
    表示存在错误。
  4. 在生成块、标签、硬件或HMI变更后,通过MCP运行或请求
    compile_check
    。在该检查通过前,不得将项目变更视为可部署状态。
  5. 除非该精确操作已获得授权,否则不得保存、归档、提交服务器会话、关闭Portal、删除或覆盖现有内容。
  6. 仅在已授权且事务支持的变更操作前后使用
    project.start_transaction()
    /
    project.end_transaction()
    ,并在所有异常路径上回滚:
python
transaction_open = False
try:
    project.start_transaction(
        undo_text="已授权的TIA变更",
        dialog_text="应用已审核的Python变更",
    )
    transaction_open = True
    # 在此处仅执行已授权的变更操作。
    project.end_transaction(rollback=False)
    transaction_open = False
except Exception:
    if transaction_open:
        project.end_transaction(rollback=True)
    raise
  1. 事务并不能使不支持的操作变得安全。如果包装器或目标对象无法提供所需的独占访问、回滚、精确选择或结果验证,请通过受保护的工作流将任务路由至C# Openness或MCP。
  2. 不得硬编码、打印或提交UMAC、安全功能、专有技术、模块访问或PLC主密钥凭据。请从用户认可的机密机制读取凭据,并仅将其传递给已明确授权的调用。
  3. 当脚本连接到用户拥有的Portal时,请在清理时使用
    portal.detach()
    。仅当脚本拥有Portal实例且已明确决定项目处置方式后,才调用
    portal.close_portal()

General coding guidance

通用编码指南

  • Prefer keyword arguments; V1.4.0 added positional and keyword handling, but keyword calls preserve intent across similar string parameters.
  • Check optional returns before dereferencing them. V1.4.3 specifically fixes a null-reference defect involving optional parameters, but callers still need to handle absent TIA objects and values.
  • Preserve Unicode paths, names, and text. V1.4.0 added non-ASCII handling.
  • Scope retrieval with
    folder_path
    when the exact group is known.
  • Never use collection position such as
    plcs[0]
    as an engineering selector.
  • Keep PLC, HMI, project, library, and live-operation functions separate so each authority boundary can be reviewed independently.
  • 优先使用关键字参数;V1.4.0新增了位置参数和关键字参数处理,但关键字调用在相似字符串参数间能保留意图。
  • 在引用前检查可选返回值。V1.4.3专门修复了涉及可选参数的空引用缺陷,但调用方仍需处理缺失的TIA对象和值。
  • 保留Unicode路径、名称和文本。V1.4.0新增了非ASCII字符处理支持。
  • 当明确知道所属组时,使用
    folder_path
    限定检索范围。
  • 绝不能使用集合位置(如
    plcs[0]
    )作为工程选择器。
  • 将PLC、HMI、项目、库和实时操作函数分开,以便独立审查每个权限边界。