2017-01-26 7 views
0

私の目標は、関数を動的に生成してファイルに保存することです。例えばのために、私の現在の試みで、create_filePythonコード生成でネストされた関数のインデントを減らす

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 

は字下げされています。どのようにインデントを減らすことができますか?私はlstripなどをすることができますが、より良い方法があるのだろうかと思います。ここStringIO(string).readlines()ダンスの必要がないことを

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

注:

+0

最もインデントのない行を探します(最初の行で十分です)。その中のインデントの量を探します。それらを書く前に、すべての行から同じ量を切り取ってください。 – 9000

答えて

3

内蔵モジュールには、textwrap.dedentの機能があります。

+0

ありがとう、私もあなたの答えを確認することができたらいいですね! – RAbraham

関連する問題