Difference between exec behavior when importing module or not

I run the following programs. It is important to note that there is a file in the directory where both of these programs are located mymodule.py.

First:

exec('''import sys
import os
os.chdir('/') 
sys.path = []
import mymodule''', {})

The second:

import mymodule
exec('''import sys
import os
os.chdir('/') 
sys.path = []
import mymodule''', {})

The first snippet picks up ImportError, as expected (in the end, the directory where mymodule is in is not in the path). The second snippet, however, does not, although mymodule is also not in its way, and the environment I am giving is empty.

My question is why

+6
source share
2 answers

According to the import system - module cache ,

, , sys.modules. , , . foo.bar.baz , sys.modules foo, foo.bar foo.bar.baz. .

sys.modules , , , . , None, NotFoundError. , Python .

mymodule; sys.modules, .

+7

exec() , sys.path script, Python .

:

. , , , mymodule.py.

[...]

, , , mymodule

. , script, . . :

<script>

Python, script, ( ), Python, , __main__.py, zip , __main__.py.

[...]

script Python, , , sys.path, __main__.

.

, mymodule.py, , , , , .

. import <module> , sys.modules . , exec .

import :

import ( ) :

  • ,
  • , import.

.

, :

import ; , .

[...]

, Python , , , .

:

, , - sys.modules. , . , foo.bar.baz , sys.modules foo, foo.bar foo.bar.baz. .

sys.modules , , , , .

, , exec() , import mymodule sys.modules[ mymodule ] exists. The second import mymodule` , .

+3

All Articles