Da die Beispiele für diesen Namensraum relativ kurz und selbsterklärend sind, werden sie nicht ausführlich erklärt. Vollständige Beispiele werden ggf. zur Verfügung gestellt.
Diese Methode erstellt ein neues Projekt.
Sie besteht aus zwei Parametern:
oEine Zeichenfolge, die den Speicherort spezifiziert, wo das Projekt gespeichert wird
oEin boolescher Parameter: Falls TRUE, wird das Projekt das neue primäre Projekt. Dieser Parameter ist optional; der Standardwert ist TRUE.
Diese Methode gibt die IProject-Instanz zurück (siehe Spezifikation im Dokument Automatisierungsplattform SDK), die für weitere Schritte verwendet werden kann.
import os
try:
# Clean up any open project
if projects.primary:
projects.primary.close()
# Define the new file name for the project
project_name = "Example.project"
# Define the new path where the new project should be stored
project_path = r"C:\Python"
# Create the new project
proj = projects.create(os.path.join(project_path, project_name), True)
# Save the project to the specified path
proj.save()
except Exception as exception:
print("Error: " + str(exception))
if not system.trace:
print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")
Diese Methode lädt ein Projekt. Geöffnete Projekte werden nicht geschlossen.
Der erste Parameter spezifiziert den Pfad des Projekts, das geladen wird.
import os
try:
# Clean up any open project
if projects.primary:
projects.primary.close()
# Define the file name for the project
project_name = "Example.project"
# Define the path where the project is stored
project_path = r"C:\Python"
# Load the existing project
proj = projects.open(os.path.join(project_path, project_name))
except Exception as exception:
print("Error: " + str(exception))
if not system.trace:
print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")
Diese Methode speichert das Projekt an seinem physischen Speicherort.
# Save project
projects.primary.save()
Diese Methode speichert das Projekt als Archiv. Diese zusätzlichen Kategorien, welche standardmäßig ausgewählt sind, sind inbegriffen, aber keine zusätzlichen Dateien.
Der erste Parameter spezifiziert den Pfad, wo das Archiv gespeichert wird.
import os
# Define the new file name for the archive
archive_name = "Example.archive"
# Define the new path where the archive should be stored
archive_path = r"C:\Python"
# Save archive with the default values
projects.primary.save_archive(os.path.join(archive_path, archive_name))
Diese Methode schließt das Projekt. Nicht gespeicherte Änderungen in diesem Projekt werden verworfen.
# Clean up any open project:
if projects.primary:
projects.primary.close()
Diese Methode sucht nach Objekten, die dem gegebenen Namen entsprechen.
Sie besteht aus zwei Parametern:
oDer erste Parameter ist der Name des gesuchten Objekts.
oDer zweite Parameter legt fest, ob eine rekursive Suche durchgeführt wird. Dieser Parameter ist optional; der Standardwert ist FALSE. Diese Methode gibt eine Sammlung von Objekten zurück.
# Search for
result_list = projects.primary.find('MyController', True)
for result in result_list:
print("Object " + result.get_name() + " found with Guid " + str(result.guid))
Namen im Baum sind nicht spezifisch Dies führt dazu, dass mehrere Objekte gefunden werden können. Die Suche läuft gegen den nicht lokalisierten Namen.
Diese Methode importiert die spezifizierten Dateien im nativen XML-Format in die oberste Ebene dieses Projekts.
import os
# Specify the project file name
project_name = "NativeImport.project"
# Define the path where the project should be/is stored
project_path = r"C:\Python"
# Define the path where the exported objects are be stored
object_path = os.path.join(project_path, "Objects")
# Create the import reporter
class Handler(NativeImportHandler):
def conflict(self, name, obj, guid):
print("Object already exists: " + name)
return NativeImportResolve.skip
def progress(self, name, obj, exception):
print("in progess: " + name)
def skipped(self, list):
return
def import_filter(name, guid, type, path):
# Workaround, skip the project settings object because we cant import it
if(type == "_3S.CoDeSys.Engine.WorkspaceObject"):
return False
return True
try:
# Clean up any open project
if projects.primary:
projects.primary.close()
# Create the new project
project_reference = projects.create(os.path.join(project_path, project_name), True)
files = os.listdir(object_path)
# Create the importer instance.
handler = Handler()
for file in files:
file_path = os.path.join(object_path, file)
project_reference.import_native(file_path, import_filter, handler)
project_reference.save()
except Exception as exception:
print("Error: " + str(exception))
if not system.trace:
print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")
Diese Methode importiert die Inhalte der spezifizierten PLCopenXML-Datei in die oberste Ebene des Projekts.
import os
# Specify the project file name
project_name = "PLCOpenXMLImport.project"
# Define the path where the project should be/is storedproject_path = r"C:\Python"
# Define the file where the exported object is stored
file_name = os.path.join(project_path, r"Objects\MyController.xml")
# Create the import reporter
class Reporter(ImportReporter):
def error(self, message):
system.write_message(Severity.Error, message)
def warning(self, message):
system.write_message(Severity.Warning, message)
def resolve_conflict(self, obj):
return ConflictResolve.Copy
def added(self, obj):
print("added: ", obj)
def replaced(self, obj):
print("replaced: ", obj)
def skipped(self, obj):
print("skipped: ", obj)
@property
def aborting(self):
return False
try:
# Clean up any open project
if projects.primary:
projects.primary.close()
# Create the reporter instance
reporter = Reporter()
# Create the new project
project_reference = projects.create(os.path.join(project_path, project_name), True)
# Import the data into the project
project_reference.import_xml(reporter, file_name)
# Save the project to the specified path
project_reference.save()
except Exception as exception:
print("Error: " + str(exception))
if not system.trace:
print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")
Diese Methode exportiert die gegebenen Objekte im nativen Format in eine Zeichenfolge, oder eine Datei an den angegebenen Pfad. Die nicht exportierbaren Objekte werden als Fehler erkannt, aber der Export wird fortgesetzt.
import sys,io,os
# Specify the project file name
project_name = "Example.project"
# Define the path where the project should be/is stored
project_path = r"C:\Python"
# Define the path where the exported objects should be stored
object_path = os.path.join(project_path, "Objects")
def collect_objects(project_reference):
# List that stores all POU nodes
project_objects = []
# Collect all the leaf nodes.
for node in project_reference.get_children(True):
project_objects.append(node)
for i in project_objects:
print("Found: ", i.type, i.guid, i.get_name())
return project_objects
def export_objects(collected_objects, project_reference):
if not os.path.exists(object_path):
os.makedirs(object_path)
# Export the files.
for candidate in collected_objects:
# Create a list of objects to export:
# The object itself
objects = [candidate]
# And sub-objects (POUs can have actions, properties, ...)
objects.extend(candidate.get_children(True))
# And the parent folders.
parent = candidate.parent
while ((not parent.is_root) and parent.is_folder):
objects.append(parent)
parent = parent.parent
# Create a unique file name
filename = os.path.join(object_path, "%s__%s.export" % (candidate.get_name(), candidate.guid))
# Print some user information
print("Exporting " + str(len(objects)) + " objects to: " + filename)
# And actually export the project
project_reference.export_native(objects, filename)
try:
# Clean up any open project
if projects.primary:
projects.primary.close()
# Open a project first
project_reference = projects.open(os.path.join(project_path, project_name))
# Collect the objects
collected_objects = collect_objects(project_reference)
export_objects(collected_objects, project_reference)
except Exception as exception:
print("Error: " + str(exception))
if not system.trace:
print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")
Diese Methode exportiert die gegebenen Objekte im PLCopenXML-Format in eine Zeichenfolge, oder eine Datei an den angegebenen Pfad. Die nicht exportierbaren Objekte werden als Fehler erkannt, aber der Export wird fortgesetzt.
import os
# Specify the object which should be exported
object_name = "MyController"
# Define the path where the exported objects should be stored
object_path = r"C:\Python\Objects"
# Define the printing function
def print_tree(treeobj, depth=0):
name = treeobj.get_name(False)
if treeobj.is_device:
deviceid = treeobj.get_device_identification()
print("{0} - {1} {2}".format(" "*depth, name, deviceid))
for child in treeobj.get_children(False):
print_tree(child, depth+1)
# Create the export reporter
class Reporter(ExportReporter):
def error(self, message):
system.write_message(Severity.Error, message)
def warning(self, message):
system.write_message(Severity.Warning, message)
def nonexportable(self, message):
print(message)
@property
def aborting(self):
return False
try:
# Get the project reference of the currently opened project
project_reference = projects.primary
# Get a reporter instance
reporter = Reporter()
# Print all devices in the project
for obj in project_reference.get_children():
print_tree(obj)
# Finds the object in the project, and return the first result
device = project_reference.find(object_name, True)
if device != None:
filename = os.path.join(object_path, device[0].get_name() + ".xml")
# Exports the object to the hard drive
project_reference.export_xml(reporter, device, filename, True, True)
except Exception as exception:
print("Error: " + str(exception))
if not system.trace:
print("Please turn on the 'Script Tracing' function to get detailed information about the script execution.")