提取Python程序代码可以通过以下几种方法:
1. 使用`inspect.getsource()`函数:
import inspect
def my_function():
print("Hello, world!")
source_code = inspect.getsource(my_function)
print(source_code)
2. 使用`dis.dis()`函数以字节码形式显示源代码:
import dis
def my_function():
print("Hello, world!")
dis.dis(my_function)
3. 使用`pygments`库以更友好的方式显示源代码:
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
def 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 ast
import astunparse
def my_function():
print("Hello, world!")
tree = ast.parse(my_function)
source_code = astunparse.unparse(tree)
print(source_code)