1

我在外部编辑器(PyScripter)中的 .py 文件中编写了一个函数。我提前将它加载到 IDLE 编辑器中,然后继续在 PyScripter 中编写函数,偶尔在加载的 .py 上使用 F5 在 IDLE 中运行它(而不在 IDLE .py 编辑器中重新加载它)。

现在,问题来了。我完成了 .py,最后一次在 PyScripter 中保存它并在 IDLE 中运行它。发现我必须做最后一次调整。不小心在 IDLE 编辑器中进行了调整,它有旧的 #$$ 版本,保存了它。PyScripter 仍在运行。当发现文件在磁盘上发生更改时重新加载文件。所有数据都没了。

我意识到了这个错误,但没有在 IDLE 中重新加载保存的 .py,所以该函数在内存中仍然可用。我可以从 IDLE shell 中取回它吗?我要精神了...

4

1 回答 1

0

你可以试试inspect.getsource()。但是,它并不总是有效。

ipython中的示例:

In [1]: import inspect

In [2]: def foo():
   ...:     print 'hello'
   ...:     

In [3]: inspect.getsource(foo)
Out[3]: u"def foo():\n    print 'hello'\n"

在 ipython 中,在导入检查之前或之后定义函数并不重要:

In [1]: def foo():
   ...:     print 'hello'
   ...:     

In [2]: import inspect

In [3]: inspect.getsource(foo)
Out[3]: u"def foo():\n    print 'hello'\n"

在基本的 cpython 交互式提示中,它根本不起作用;

Python 2.7.3 (default, Jul 26 2012, 19:08:05) 
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
...   print 'hello'
... 
>>> import inspect
>>> inspect.getsource(foo)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/inspect.py", line 701, in getsource
    lines, lnum = getsourcelines(object)
  File "/usr/local/lib/python2.7/inspect.py", line 690, in getsourcelines
    lines, lnum = findsource(object)
  File "/usr/local/lib/python2.7/inspect.py", line 538, in findsource
    raise IOError('could not get source code')
IOError: could not get source code
>>> def bar():
...   print 'second try'
... 
>>> inspect.getsource(bar)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/inspect.py", line 701, in getsource
    lines, lnum = getsourcelines(object)
  File "/usr/local/lib/python2.7/inspect.py", line 690, in getsourcelines
    lines, lnum = findsource(object)
  File "/usr/local/lib/python2.7/inspect.py", line 538, in findsource
    raise IOError('could not get source code')
IOError: could not get source code

我没有尝试 IDLE,因为我基本上从不使用它。我更喜欢 ipython 进行交互式实验和使用 emacs 进行编辑。

于 2012-12-20T02:30:15.357 回答