我的目标是动态生成函数,然后将它们保存在文件中。例如,在我当前的尝试中,调用create_file
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/代码.py'):
^{pr2}$我得到的输出是('/tmp/代码.py'):
def a_nested_func(b, k):
return b, k
def a_root_func(x):
pass
a_nested_func
缩进。如何减少压痕?我可以做lstrip
等等,但是我想知道有没有更好的方法。在
使用^{} function 删除常见的前导空格:
注意这里不需要跳
StringIO(string).readlines()
舞。在内置模块中有一个函数,^{} 。在
相关问题 更多 >
编程相关推荐