Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the best way to write python code into a python file?

Tags:

python

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!

like image 830
Jurudocs Avatar asked Aug 05 '12 09:08

Jurudocs


2 Answers

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.'
like image 195
unutbu Avatar answered Oct 03 '22 20:10

unutbu


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."
like image 38
Karoly Horvath Avatar answered Oct 03 '22 20:10

Karoly Horvath