What is the best way to write python code to a python file?

I want to write a script (generate_script.py) that generates another python script (file generated .py)

So far I have created 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.' 

The file (filegenerated.py) now looks like this:

def print_success (): print "sucesss"

Now I don’t want to manually insert all line breaks (also due to problems with the operating system) ... is there a template system that I can use to write python code to a python file? Does anyone have an example?

Thanks a lot!

+6
source share
4 answers

You can simply 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 split when writing to a separate file, you can 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.' 
+4
source
 lines = [] lines.append('def print_success():') lines.append(' print "sucesss"') "\n".join(lines) 

If you are 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 can add additional methods, add new lines to the block and all that, 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 

Conclusion:

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

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

for conclusion

 def print_success(): print "sucesss" 

or multi-line

 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
source

untubu's answer is probably a more pythonic answer, but your code sample lacks new string characters and tabs.

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

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

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

+2
source

Source: https://habr.com/ru/post/922151/


All Articles