2017-01-26 35 views
0

我的目標是動態生成函數,然後將它們保存在文件中。對於例如,在我目前的嘗試中,在調用create_file減少Python代碼生成中嵌套函數的縮進

import io 


def create_file(): 
    nested_func = make_nested_func() 
    write_to_file([nested_func, a_root_func], '/tmp/code.py') 


def a_root_func(x): 
    pass 


def make_nested_func(): 
    def a_nested_func(b, k): 
     return b, k 

    return a_nested_func 


def write_to_file(code_list, path): 
    import inspect 
    code_str_list = [inspect.getsource(c) for c in code_list] 
    with open(path, 'w') as ofh: 
     for c in code_str_list: 
      fh = io.StringIO(c) 
      ofh.writelines(fh.readlines()) 
      ofh.write('\n') 


create_file() 

我想輸出是( '/ tmp目錄/ code.py'):

def a_nested_func(b, k): 
     return b, k 

def a_root_func(x): 
    pass 

我得到的輸出是('/ tmp目錄/code.py'):

def a_nested_func(b, k): 
     return b, k 

def a_root_func(x): 
    pass 

a_nested_func是縮進的。我怎樣才能減少縮進?我可以做lstrip等,但我不知道是否有更好的方法。

+0

查找最小縮進行(可能是第一個就足夠了)。找到其中的縮進量。寫入之前從所有行中剪下相同的數量。 – 9000

回答

3

使用textwrap.dedent() function去除常見的前導空格:

import inspect 
from textwrap import dedent 

def write_to_file(code_list, path): 
    code_str_list = [inspect.getsource(c) for c in code_list] 
    with open(path, 'w') as ofh: 
     for c in code_str_list: 
      dedented = dedent(c) 
      ofh.write(dedented + '\n') 

注意,沒有必要對這裏StringIO(string).readlines()舞蹈。

3

內置模塊有一個功能,textwrap.dedent

import textwrap 
s = """ 
    abc 
    def 
""" 
s2 = """ 
abc 
    def 
""" 
assert textwrap.dedent(s) == s2 
+0

謝謝,希望我也能檢查你的答案! – RAbraham