17

我想写一个脚本(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(): 打印“成功”

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

非常感谢!

4

4 回答 4

14

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

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.'
于 2012-08-05T10:05:53.027 回答
11
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."
于 2012-08-05T10:10:29.153 回答
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.'

输出

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.'
于 2012-08-05T10:07:01.240 回答
2

untubu 答案可能是更 Pythonic 的答案,但在您的代码示例中,您缺少换行符和制表符。

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

这将为您提供间距和换行符。下面的链接将为您提供一些关于接受的提示。

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

于 2012-08-05T10:12:35.860 回答