How to get the current script's code in Python?

落花浮王杯 提交于 2019-12-04 09:35:23

Try:

import inspect
import sys

print inspect.getsource(sys.modules[__name__])

Or even:

import inspect
import sys

lines = inspect.getsourcelines(sys.modules[__name__])[0]

for index, line in enumerate(lines):
    print "{:4d} {}".format(index + 1, line)

The file the code is contained inside is considered to be a Python "module", and sys.modules[__name__] returns a reference to this module.

Edit

Or even, as @ilent2 suggested, like this, without the need of the sys module:

import inspect

print inspect.getsource(inspect.getmodule(inspect.currentframe()))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!