#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
from scriptengine import *
def export_st_recursive(obj, base_path):
"""再帰的にオブジェクトを探索し、STコードをエクスポートする"""
try:
current_path = base_path
obj_name = obj.get_name() if hasattr(obj, "get_name") else "unknown"
print("Processing: " + obj_name)
if hasattr(obj, "is_folder") and obj.is_folder:
folder_path = os.path.join(current_path, obj_name)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
for child in obj.get_children():
export_st_recursive(child, folder_path)
else:
has_content = False
filename = os.path.join(current_path, obj_name + ".st")
if hasattr(obj, "has_textual_declaration") and obj.has_textual_declaration:
with open(filename, "w", encoding='utf-8') as f:
f.write(obj.textual_declaration.text)
has_content = True
if hasattr(obj, "has_textual_implementation") and obj.has_textual_implementation:
with open(filename, "a" if has_content else "w", encoding='utf-8') as f:
f.write("\n\n" + obj.textual_implementation.text)
has_content = True
if has_content:
print("Exported: " + filename)
if hasattr(obj, "get_children"):
for child in obj.get_children():
export_st_recursive(child, base_path)
except Exception as e:
print("オブジェクト処理中にエラーが発生しました: " + str(e))
def export_st_code(base_path):
try:
prj = projects.primary
device = next((obj for obj in prj.get_children() if obj.get_name() == "Device"), None)
plc_logic = next((obj for obj in device.get_children() if obj.get_name() == "Plc Logic"), None)
application = next((obj for obj in plc_logic.get_children() if obj.get_name() == "Application"), None)
if application is None:
print("Applicationオブジェクトが見つかりませんでした")
return
for obj in application.get_children():
export_st_recursive(obj, base_path)
print("Export completed successfully")
except Exception as e:
print("エラーが発生しました: " + str(e))
if __name__ == "__main__":
export_path = "C:\\path\\to\\export"
export_st_code(export_path)
このスクリプトを実行すると、CODESYS プロジェクト内の ST コードが指定したディレクトリにエクスポートされます。