[Q] ImportError by __import__() on Python >= 3.4

MRAB python at mrabarnett.plus.com
Fri Jun 3 14:15:52 EDT 2016


On 2016-06-03 06:48, Makoto Kuwata wrote:
> On Fri, Jun 3, 2016 at 9:31 AM, MRAB <python at mrabarnett.plus.com 
> <mailto:python at mrabarnett.plus.com>> wrote:
>
>     On 2016-06-02 15:04, Makoto Kuwata wrote:
>
>         Hi,
>
>         I have a trouble around __import__().
>         The following sample code works well on Python <= 3.3,
>         but it raises ImportError on Python >= 3.4.
>
>
>             ## importtest.py
>             import sys, os, shutil
>
>             def test(name):
>                 try:
>                     ## create 'foo/__init__.py' file
>                     os.mkdir(name)
>                     with open(name + "/__init__.py", 'w') as f:
>                         f.write("X=1")
>                         f.flush()
>                     ## ipmort 'foo' module
>                     mod = __import__(name)
>                 finally:
>                     if os.path.isdir(name):
>                         shutil.rmtree(name)
>
>             test("foo")    # no errors
>             test("bar")    # may raise error on Python >= 3.4. Why?
>
>
>         Output Example:
>
>             ### No errors  (Python <= 3.3)
>             ubuntu$ export PYTHONPATH=.
>             ubuntu$ for x in 1 2 3 ; do /usr/bin/python3.3
>         importtest.py; done
>
>             ### ImportError (Python >= 3.4)
>             ubuntu$ export PYTHONPATH=.
>             ubuntu$ for x in 1 2 3 ; do /usr/bin/python3.4
>         importtest.py; done
>             Traceback (most recent call last):
>               File "tmp/importtest.py", line 19, in <module>
>                 test("bar")    # may raise error on Python >= 3.4. Why?
>               File "tmp/importtest.py", line 13, in test
>                 mod = __import__(name)
>             ImportError: No module named 'bar'
>
>
>         Please give me any advices or hints.
>         Thanks.
>
>     Things to try:
>
>     Does the order matter? If you try "bar" then "foo" does "foo" fail?
>
>
> Yes. Name is not matter. Order is matter.
>
>
>     Does the directory matter?
>
>
> No. I created "foo" and "bar" directories in order to create python 
> module.
>
>
>     Is there something called "bar" in the directory already?
>
>
> No. Sample script removes directories every time.
>
>
>     What does the created "bar" directory contain? Does it really
>     contain only "__init__.py"?
>
>
> Yes. See sample script for detail.
>
>     You're testing the script 3 times; on which iteration does it fail?
>
>
> Because sometimes script will fail and sometimes will work file.
>
It sounds like it's some kind of race condition, e.g. it hasn't finished 
writing the file before it does the import.




More information about the Python-list mailing list