【问题标题】:How to get the current script's code in Python?如何在 Python 中获取当前脚本的代码?
【发布时间】:2015-12-28 10:29:47
【问题描述】:

我想获取当前脚本作为 Python 变量中的字符串。

我找到了两种次优的方法,但我希望有更好的解决方案。我发现:

  1. inspect 导入有一个 getsource 方法,但它只返回一个函数(或类或其他)的代码,而不是整个脚本。我找不到将整个脚本的对象传递给getsource的方法。

  2. 我可以使用__file__sys.argv[0]open 找到脚本文件的文件位置以进行读取。但这对我来说似乎太间接了。

那么:有没有(更好的)方法可以将整个脚本作为字符串访问?

如果相关:我更喜欢 Python 2.7 解决方案而不是 3.x。

【问题讨论】:

  • 你到底想实现什么?
  • 可能重复here.
  • 看起来不太一样,提供的答案并没有真正显示如何访问脚本自己的代码,而是其他脚本的代码。
  • @jonrsharpe 这是一个代码高尔夫球谜题。
  • @jonrsharpe:我也有同样的问题。就我而言,我有一个将结果转储到文件中的数据处理脚本,我想准确地记录/如何/它与结果一起执行它。

标签: python self-reference


【解决方案1】:

试试:

import inspect
import sys

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

甚至:

import inspect
import sys

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

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

其中包含代码的文件被认为是一个 Python“模块”,sys.modules[__name__] 返回对该模块的引用。

编辑

甚至,正如@ilent2 建议的那样,不需要sys 模块:

import inspect

print inspect.getsource(inspect.getmodule(inspect.currentframe()))

【讨论】:

  • 或者,导入较少但可读性较差:inspect.getsource(inspect.getmodule(inspect.currentframe()))
猜你喜欢
  • 2011-05-08
  • 2013-02-06
  • 1970-01-01
  • 2011-01-07
  • 2013-03-16
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多