Python:__import__ 在 REPL 中有效,但在脚本中无效

标签 python module

我在这里很困惑。我有一个目录 root ,其子目录 foo 包含文件 __init__.py。如果我从 root 在 python REPL 中运行以下命令,它可以正常工作:

Python 2.7.5 (default, Aug 25 2013, 00:04:04) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.chdir('foo')
>>> print __import__('foo')
<module 'foo' from 'foo/__init__.pyc'>
>>> 

但是,如果我将相同的命令放入脚本 root/import_foo.py 中,则会失败:

import os
os.chdir('foo')
print __import__('foo')


> python import_foo.py
Traceback (most recent call last):
  File "import_foo.py", line 3, in <module>
    print __import__('foo')
ImportError: No module named foo

为什么会出现这样的差异?我该如何纠正这个问题?

最佳答案

已经问了很久了,但我在这个问题上浪费了一个小时,解决方案是在 os.chdir 之后 sys.path.append(".");

全文: https://mail.python.org/pipermail/python-bugs-list/2004-June/023835.html

In Python 2.3a2 in non-interactive mode an import after an os.chdir does not import the module in the new current directory after the os.chdir. Instead it attempts to import a module (if present) by that name in the previous current directory before the os.chdir. If there is not a module by that name in the previous current directory, there is an ImportError exception.

$ mkdir -p some/dir/with/python/
$ cat > some/dir/with/python/example.py
x = 17
$ cat > import_test.py
import os
cwd = os.getcwd()
os.chdir("some/dir/with/python")        
m = __import__("example")
print(m)
os.chdir(cwd)
$ python3 import_test.py
Traceback (most recent call last):
File "import_test.py", line 4, in <module>
m = __import__("example")
ImportError: No module named 'example'

但是:

$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.chdir("some/dir/with/python")
>>> __import__("example")
<module 'example' from '/tmp/some/dir/with/python/example.py'>
>>> 

还有“.”在系统路径中:

$ cat > import_test.py
import sys
import os
cwd = os.getcwd()
os.chdir("some/dir/with/python")  
sys.path.append(".")
m = __import__("example")
print(m)
os.chdir(cwd)
$ python3 import_test.py
<module 'example' from './example.py'>
$ 

关于Python:__import__ 在 REPL 中有效,但在脚本中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22259909/

相关文章:

python - 命名python模块有什么要求?

c - 如何发送自己的协议(protocol)包?

python - 在python中导入系统模块

perl - 事件状态 Perl : Unable to download modules using ppm

c - 避免暴露已编译 C 模块的详细信息

python - 在 python 的虚拟环境中 pip install 后无法导入tensorflow

python - 当我通过类名访问类的属性时,Python 调用了什么方法?

python - Django - 将 InMemoryUploadedFile 发布到外部 REST api

python - 列表元素的计数器

python - 自定义元素类查找未加载自定义元素