尽管不建议这样做,但您可以这样做:
- 启动会话会保存 、 和全局变量的
sys.modules
状态sys.path
。
- 无论发生什么都会对这些(也许还有其他)产生一些影响。
- 停止会话将恢复先前启动的会话的状态。
您应该注意,这并不完美,也不推荐。我真的看不出有什么问题,import sympy
而不是from sympy import *
.
编辑:
似乎访问和修改全局范围并不容易,并且会给您带来很多麻烦……例如:
class Session(object):
def __init__(self, gref):
self.init()
self.gref = gref
def init(self):
self.modules = {}
self.path = None
self.glob = {}
def start(self):
import sys
self.modules = sys.modules.copy()
self.path = sys.path[:]
self.glob = self.gref.copy()
self.gref['test'] = 'abc'
def stop(self):
import sys
sys.modules = self.modules.copy()
sys.path = self.path[:]
for k in self.gref.keys():
del self.gref[k]
self.gref.update(self.glob)
def __repr__(self):
return repr(self.glob)
运行它:
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sessionpy import Session
>>> s = Session(globals())
>>> before = 123
>>> s.start()
>>> after = 456
>>> s.stop()
>>> after
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'after' is not defined
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/apport_python_hook.py", line 66, in apport_excepthook
from apport.fileutils import likely_packaged, get_recent_crashes
File "/usr/lib/python2.7/dist-packages/apport/__init__.py", line 1, in <module>
from apport.report import Report
File "/usr/lib/python2.7/dist-packages/apport/report.py", line 18, in <module>
import problem_report
File "/usr/lib/python2.7/dist-packages/problem_report.py", line 15, in <module>
from email.encoders import encode_base64
File "/usr/lib/python2.7/email/__init__.py", line 115, in <module>
setattr(sys.modules['email'], _name, importer)
KeyError: 'email'
Original exception was:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'after' is not defined
>>> before
123
>>>
您可以看到它有效(因为after
引发 a NameError
)但是sys.excepthook
. 我只能想象使用 2 个大型库(例如sympy
和numpy
.
注意:
如果你只想运行一个简单的东西,你可以把全局变量弄乱,你会没事的。