I want to write a script (generate_script.py) generating another python script (filegenerated.py)
So far i have created generate_script.py:
import os
fil
lines = []
lines.append('def print_success():')
lines.append(' print "sucesss"')
"\n".join(lines)
If you're building something complex dynamically:
class CodeBlock():
def __init__(self, head, block):
self.head = head
self.block = block
def __str__(self, indent=""):
result = indent + self.head + ":\n"
indent += " "
for block in self.block:
if isinstance(block, CodeBlock):
result += block.__str__(indent)
else:
result += indent + block + "\n"
return result
You could add some extra methods, to add new lines to the block and all that stuff, but I think you get the idea..
Example:
ifblock = CodeBlock('if x>0', ['print x', 'print "Finished."'])
block = CodeBlock('def print_success(x)', [ifblock, 'print "Def finished"'])
print block
Output:
def print_success(x):
if x>0:
print x
print "Finished."
print "Def finished."