You have to use
textual_implementation and
textual_declaration properties of IScriptTextDocument.
There are few methods like replace, insert, append and so on (see ScriptEngine.chm for more information).
Code:
proj = projects.primary
found = proj.find("Application", True)
app = found[0]
# Create FB
mypou = app.create_pou("MyPou")
# Change declaration of the FB
implementation = mypou.textual_declaration.replace("""FUNCTION_BLOCK MyPou
VAR_INPUT
iValue : INT;
END_VAR
VAR_OUTPUT
END_VAR
VAR
END_VAR""")
# Change implementation of the FB
mypou.textual_implementation.replace("""iValue := iValue + 1;""")
# Add method to FB
dosomething = mypou.create_method("DoSomething", "INT")
# Change declaration of the method
dosomething.textual_declaration.replace("""METHOD DoSomething : INT
VAR_INPUT
iVal1 : INT;
iVal2 : INT;
END_VAR""")
# Change implementation of the method
dosomething.textual_implementation.replace("""DoSomething := iVal1 + iVal2;""")
# Find the pou and delete it
found = app.find("MyPou")
if found and len(found) == 1:
found[0].remove()
else:
print("POU 'MyPou' was not found"