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
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
file = open(file_name, 'w')
file.write('def print_success():')
file.write(' print "sucesss"')
file.close()
print 'Execution completed.'
The file (filegenerated.py) looks now like this:
def print_success(): print "sucesss"
Now i don't want to manually insert all linebreaks (also due to operating system difficulties)...is there a template system i can use writing python code into a python file? Does someone have an example?
Thanks a lot!
You could just use a multiline string:
import os
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
with open(file_name, 'w') as f:
f.write('''\
def print_success():
print "sucesss"
''')
print 'Execution completed.'
If you like your template code to be indented along with the rest of your code, but dedented when written to a separate file, you could use textwrap.dedent
:
import os
import textwrap
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
with open(file_name, 'w') as f:
f.write(textwrap.dedent('''\
def print_success():
print "sucesss"
'''))
print 'Execution completed.'
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With