提取Python程序代码可以通过以下几种方法:
1. 使用`inspect.getsource()`函数:
import inspectdef my_function():print("Hello, world!")source_code = inspect.getsource(my_function)print(source_code)
2. 使用`dis.dis()`函数以字节码形式显示源代码:
import disdef my_function():print("Hello, world!")dis.dis(my_function)
3. 使用`pygments`库以更友好的方式显示源代码:
from pygments import highlightfrom pygments.lexers import PythonLexerfrom pygments.formatters import HtmlFormatterdef my_function():print("Hello, world!")source_code = inspect.getsource(my_function)formatter = HtmlFormatter()highlighted_code = highlight(source_code, PythonLexer(), formatter)print(highlighted_code)
4. 直接打开源代码文件(如果它是一个独立的文件):
假设源代码保存在 my_script.py 文件中with open('my_script.py', 'r') as file:source_code = file.read()print(source_code)
5. 使用`help()`函数和交互式Python解释器:
在交互式解释器中>>> import math>>> help(math)
6. 使用第三方库`astunparse`导出源代码:
import astimport astunparsedef my_function():print("Hello, world!")tree = ast.parse(my_function)source_code = astunparse.unparse(tree)print(source_code)

