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

后端 未结 4 1022
独厮守ぢ
独厮守ぢ 2021-02-07 10:47

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         


        
相关标签:
4条回答
  • 2021-02-07 10:50
    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."
    
    0 讨论(0)
  • 2021-02-07 11:11

    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.'
    
    0 讨论(0)
  • 2021-02-07 11:11

    Try using \n and \t

    import os
    filepath = os.getcwd()
    def MakeFile(file_name):
        temp_path = filepath + file_name
        file = open(file_name, 'w')
        file.write('def print_success():\n')
        file.write('\tprint "sucesss"')
        file.close()
        print 'Execution completed.'
    

    to output

    def print_success(): 
        print "sucesss"
    

    or multiline

    import os
    filepath = os.getcwd()
    def MakeFile(file_name):
        temp_path = filepath + file_name
        file = open(file_name, 'w')
        file.write('''
    def print_success():
        print "sucesss"
        ''')
        file.close()
        print 'Execution completed.'
    
    0 讨论(0)
  • 2021-02-07 11:15

    untubu answer is probably the more pythonic answer, but in your code example you're missing new line chars and tabs.

    file.write("def print_success():\n")
    file.write('\tprint "success"\n\n')
    

    This will give you the spacing and newlines. The link below will give you some tips on the accepted ones.

    http://docs.python.org/release/2.5.2/ref/strings.html

    0 讨论(0)
提交回复
热议问题