我想写一个脚本(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文件?有人有例子吗?
非常感谢!
答案 0 :(得分:7)
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."
答案 1 :(得分:5)
您可以使用多行字符串:
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.'
答案 2 :(得分: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.'
答案 3 :(得分:2)
untubu回答可能是更加pythonic的答案,但在您的代码示例中,您缺少新的行字符和标签。
file.write("def print_success():\n")
file.write('\tprint "success"\n\n')
这将为您提供间距和换行符。下面的链接将为您提供有关已接受的提示。