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

2024-04-18 19:25:44 发布

您现在位置: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.'

文件(filegenerated.py)现在如下所示:

def print_success(): print "sucesss"

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

非常感谢!


Tags: 文件namepy脚本osdefscriptgenerate
3条回答

尝试使用\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.'

输出

def print_success(): 
    print "sucesss"

或多行

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.'
lines = []
lines.append('def print_success():')
lines.append('    print "sucesss"')
"\n".join(lines)

如果动态构建复杂的对象:

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

你可以添加一些额外的方法,在块中添加新的行和所有的东西,但是我想你明白了。。

示例:

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

输出:

def print_success(x):
    if x>0:
        print x
        print "Finished."
    print "Def finished."

您可以使用多行字符串:

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.'

如果希望模板代码与其余代码缩进,但在写入单独的文件时将其删除,则可以使用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.'

相关问题 更多 >