on perhaps unloading modules?

Hope Rouselle hrouselle at jevedi.com
Fri Aug 20 14:15:45 EDT 2021


Chris Angelico <rosuav at gmail.com> writes:

> On Tue, Aug 17, 2021 at 4:02 AM Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
>> The second best way would be to not use import_module, but to
>> exec() the student's code. That way you don't create an entry in
>> sys.modules and don't have to worry about somehow unloading the
>> module.
>
> I would agree with this. If you need to mess around with modules and
> you don't want them to be cached, avoid the normal "import" mechanism,
> and just exec yourself a module's worth of code.

This is looks very interesting.

--8<---------------cut here---------------start------------->8---
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> >>> code
<function code at 0x009F5660>
>>> code()
'def p():\n  import math\n  return math.e\n'
>>> p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'p' is not defined
>>> exec(code())
>>> p
<function p at 0x0113F5D0>
>>> p()
2.718281828459045
--8<---------------cut here---------------end--------------->8---

This is also totally unsafe, right?  But at least it won't give me those
loading problems I had before.  But I think I'm gonna go with Greg
Ewing's first option --- running it all on a separate process, computing
that report I was computing, then printing it out to the stdout and
reading it from a controller process to know the student's results.

This way I'm one step closer to safety --- I could chroot it and give it
a limited period of time for execution.  I suppose I could also
customize Python's environment to only allow the modules I'd like to
allow as well as the builtins I'd like to allow.  (That would be
interesting as well.)

So, alright, let me learn how to spawn a process.  Thanks very much.


More information about the Python-list mailing list