什么是将python代码写入python文件的最佳方法?

Jur*_*ocs 10 python

我想写一个脚本(generate_script.py)生成另一个python脚本(filegenerated.py)

到目前为止,我已经创建了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.'
Run Code Online (Sandbox Code Playgroud)

文件(filegenerated.py)现在看起来像这样:

def print_success():print"sucesss"

现在我不想手动插入所有换行符(也是由于操作系统的困难)...是否有模板系统我可以使用python代码写入python文件?有人有例子吗?

非常感谢!

Kar*_*ath 8

lines = []
lines.append('def print_success():')
lines.append('    print "sucesss"')
"\n".join(lines)
Run Code Online (Sandbox Code Playgroud)

如果您正在动态构建复杂的东西:

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
Run Code Online (Sandbox Code Playgroud)

你可以添加一些额外的方法,为块添加新行和所有这些东西,但我想你明白了...

例:

ifblock = CodeBlock('if x>0', ['print x', 'print "Finished."'])
block = CodeBlock('def print_success(x)', [ifblock, 'print "Def finished"'])
print block
Run Code Online (Sandbox Code Playgroud)

输出:

def print_success(x):
    if x>0:
        print x
        print "Finished."
    print "Def finished."
Run Code Online (Sandbox Code Playgroud)


unu*_*tbu 6

您可以只使用多行字符串:

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.'
Run Code Online (Sandbox Code Playgroud)

如果您希望模板代码与其余代码一起缩进,但在写入单独文件时缩进,则可以使用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.'
Run Code Online (Sandbox Code Playgroud)


bma*_*ign 5

尝试使用 \n 和 \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.'
Run Code Online (Sandbox Code Playgroud)

输出

def print_success(): 
    print "sucesss"
Run Code Online (Sandbox Code Playgroud)

或多行

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.'
Run Code Online (Sandbox Code Playgroud)