【问题标题】:Python - Code snippet not working on Python 2.5.6, using IDLEPython - 代码片段不适用于 Python 2.5.6,使用 IDLE
【发布时间】:2010-06-02 17:10:31
【问题描述】:

我正在为一个大学项目使用一段自修改代码。

这里是:

import datetime
import inspect
import re
import sys

def main():
    # print the time it is last run
    lastrun = 'Mon Jun  8 16:31:27 2009'

    print "This program was last run at ",
    print lastrun

    # read in the source code of itself
    srcfile = inspect.getsourcefile(sys.modules[__name__])
    f = open(srcfile, 'r')
    src = f.read()
    f.close()

    # modify the embedded timestamp
    timestamp = datetime.datetime.ctime(datetime.datetime.now())
    match = re.search("lastrun = '(.*)'", src)
    if match:
        src = src[:match.start(1)] + timestamp + src[match.end(1):]

    # write the source code back
    f = open(srcfile, 'w')
    f.write(src)
    f.close()

if __name__=='__main__':
    main()

不幸的是,它不起作用。返回错误:

# This is the script's output
This program is last run at  Mon Jun  8 16:31:27 2009
# This is the error message
Traceback (most recent call last):
  File "C:\Users\Rui Gomes\Desktop\teste.py", line 30, in <module>
    main()
  File "C:\Users\Rui Gomes\Desktop\teste.py", line 13, in main
    srcfile = inspect.getsourcefile(sys.modules[__name__])
  File "C:\Python31\lib\inspect.py", line 439, in getsourcefile
    filename = getfile(object)
  File "C:\Python31\lib\inspect.py", line 401, in getfile
    raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module '__main__' (built-in)> is a built-in module

感谢您提供任何解决方案。

【问题讨论】:

  • 自修改代码是邪恶的。任何语言。
  • 检查你的路径,你是从 IDLE 2.5.6 调用 \Python31\lib 资源吗?
  • 哇,这是个坏主意。为什么不能在其他地方记录运行时?
  • 这只是概念证明。学术好奇心。
  • 而且很难调试。你还需要什么证据证明这是个坏主意?

标签: python python-idle python-2.5 self-modifying


【解决方案1】:

它在 IDLE 之外运行时运行完美——因此问题不在于您的代码本身,而在于您执行它的环境。当您在 IDLE 中运行代码的错误部分时,您会得到以下输出:

>>> import inspect
>>> sys.modules[__name__]
<module '__main__' from 'C:\Python26\Lib\idlelib\idle.pyw'>
>>> inspect.getsourcefile(sys.modules[__name__])
'C:\\Python26\\Lib\\idlelib\\idle.pyw'

当您 IDLE

中运行时
# read in the source code of itself
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'r')
src = f.read()
f.close()

您实际上是在尝试修改'C:\\Python26\\Lib\\idlelib\\idle.pyw' ... IDLE 不允许您这样做。

总而言之,您所写的内容似乎确实有效:但它不能在 IDLE 中运行。

【讨论】:

  • 问题与openfile部分无关,因为异常是在inspect.getsourcefile(sys.modules[name])中触发的
【解决方案2】:

您可以使用__file__ 全局属性来获取当前模块的源路径。

来自 2.6 文档:

__file__ 是加载模块的文件的路径名,如果 它是从文件中加载的。这 __file__ 属性对于静态链接的 C 模块不存在 进入口译员;用于扩展 从一个动态加载的模块 共享库,它是路径名 共享库文件。

编辑:

我假设 inspect.getsourcefile() 在检查 __main__ 模块时总是会抛出 TypeError。只有从交互式解释器运行时才会出现这种情况。我站得更正了。得了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多