[英]Can I copy across selected python functions and class methods from one file to another file?
I have a python file that is a collection functions
, classes
with methods
etc. I need to parse it so that I can just extract out the specified functions
and classes
including the methods
that I need for the purpose of over-riding them. 我有一个python文件,它是一个集合functions
,带有methods
classes
等。我需要对其进行解析,以便我可以提取出指定的functions
和classes
包括为覆盖它们而需要的methods
。
Is there a parser
that can parse python
code well for this kind of requirement? 是否有一种parser
可以很好地解析python
代码来满足这种需求? Will the inbuilt ast
module help me? 内置的ast
模块对我有帮助吗?
For example: 例如:
Input: Main.py 输入:Main.py
def f_one():
"""
"""
pass
class c_one():
"""
"""
def m_one():
"""
"""
pass
def m_two():
"""
"""
pass
def m_three():
"""
"""
pass
class c_two():
def m_one():
"""
"""
pass
Goal is to just copy across f_one
, c_one
and m_one
, more generally the code (function, class etc) that I specify. 目标是跨f_one
, c_one
和m_one
,更一般地,我指定的代码(函数,类等)会复制。
Output: Copy.py 输出:Copy.py
def f_one():
"""
"""
pass
class c_one():
"""
"""
def m_one():
"""
"""
pass
You just need to import it: 您只需要导入它:
from Main import f_one, c_one
c = c_one()
c.m_two()
You can use inspect.getsource()
您可以使用inspect.getsource()
import inspect
import Main
objects = [Main.f_one, Main.c_one]
copy = ''
#copy objects
for obj in objects:
copy += inspect.getsource(obj)
copy += '\n'
with open('Copy.py', 'w') as out:
out.write(copy)
This writes the full source code of f_one
and c_one
to Copy.py. 这会将f_one
和c_one
的完整源代码写入Copy.py。 If you only want parts of c_one
, you would have to inspect all the members that you want seperately (eg inspect.getsource(Main.c_one.m_one)
) and assemble them manually. 如果只希望使用c_one
,则必须分别检查所有想要的成员(例如inspect.getsource(Main.c_one.m_one)
)并手动组装它们。
You can also use inspect.getsourcelines()
to get an object's source line by line (for instance if you want only the headers). 您还可以使用inspect.getsourcelines()
获取对象的源代码(例如,如果您仅需要标题)。
Note that this is obviously not possible for imports from compiled files. 请注意,这对于从编译文件导入显然是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.