Python script to automate 'Find and Replace'

swtroelofs
2017-09-13
2017-09-14
  • swtroelofs - 2017-09-13

    Hi all,

    I'm new to Python scripts and I am wondering if this is possible to script:

    Before finishing a project I always run a couple of Find and Replace actions (with regex), for example:
    Find: [\t ]+(\n)
    Replace: $1

    Can I make a Python script that automates this process? So it runs a couple of Find and replace actions in a row?

    Will it use native CODESYS Find and replace functionality, or do I just program a regex search in Python?

    Thanks

     
  • mkeller - 2017-09-14

    Hi swtroelofs.

    swtroelofs hat geschrieben:
    Will it use native CODESYS Find and replace functionality, or do I just program a regex search in Python?

    Not at the moment but you could use the IScriptTextDocument interface to search and change the Structured Text (ST) parts of the POUs.

    Here some example code for finding the textual parts:

    def getFullName(obj):
       str = ""
       while obj is not None and not obj.is_root:
          str = obj.get_name() + '.' + str
          obj = obj.parent
       return str
    proj = projects.primary
    \# Iterate through all children of the project
    for child in proj.get_children(True):
       hasDecl = child.has_textual_declaration
       hasImpl = child.has_textual_implementation
       if hasDecl or hasImpl:
          print("=== Object with text: {} declaration={} implementation={}".format(getFullName(child), hasDecl, hasImpl))
          if hasDecl:
             declaration = child.textual_declaration
             print("Length of declaration: " + str(declaration.length))
             print("Content of declaration:\n<code>")
             print(declaration.text)
             print("</code>")
          if hasImpl:
             implementation = child.textual_implementation
             print("Length of implementation: " + str(implementation.length))
             print("Content of implementation:\n<code>")
             print(implementation.text)
             print("</code>")
    

    To change the content of a textual part you use the method . There are more methods you can use, see the Scripting API documentation.

    BR
    Martin

     

Log in to post a comment.