【问题标题】:Windows Python v. Linux Python: "from module import *" is not importing on WindowsWindows Python v. Linux Python:“从模块导入 *”不在 Windows 上导入
【发布时间】:2015-08-16 18:56:37
【问题描述】:

有我认为是一个不寻常的问题。我有一个 Python 脚本 script1.py 定义 class BaseClass(dict),还有另一个脚本定义 class ChildClass(BaseClass)

ChildClass 使用from script1 import * 导入第一个脚本,但是当尝试运行ChildClass 时,我得到NameError: name 'BaseClass' is not defined

# script1.py
...
class BaseClass(dict):
    def __init__(self, params):
        pass
...

# ChildClass.py
from script1 import *

class ChildClass(BaseClass):
...

完全相同的脚本在我的家用机器 (Ubuntu 15.04) 上运行良好,但我的工作机器 (Windows 7 Pro) 出现上述 NameError。

我在python环境中检查过,确实找到了script1.py文件,但实际上并没有导入里面的任何函数。

>>> from script1 import *
>>> BaseClass
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'BaseClass' is not defined'

我在想问题是 Windows Python 和 Linux Python 之间的区别,但我以前从未遇到过这种问题。欢迎任何见解。

【问题讨论】:

  • 您在sys.path 的某个文件夹中还有一些名为script1 的其他脚本,它不包含BaseClass。试试import script1; print script1.__file__
  • 执行import script1,然后打印script1.__file__,看看它在哪里找到模块。
  • @kindall @Brenbarn 这样做会导致AttributeError: 'module' object has no attribute '__file__。不过,我知道它正在读取 script1,因为尝试输入 import randomstringao 会引发 ImportError。
  • 这个模块的实际名称是什么?因为你得到的错误通常表明一个内置模块。
  • 您确定两台计算机都使用 Python 2 吗? Python 2 和 3 的相对导入规则有些不同,it looks like you're getting the built-in parser module on one machine.

标签: python linux windows python-2.7 python-import


【解决方案1】:

原来(假设命名)script1 与内置 Python 模块共享一个名称。我的家用机器上似乎没有发生错误,因为我在那里运行 Python 3,而在我的工作机器上运行 Python 2。

为了解决这个问题,我简单地重命名了script1

【讨论】:

  • 哦,对不起,应该指定。 script1 只是一个占位符。实际上是parser
猜你喜欢
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 2012-08-08
  • 2014-12-10
  • 1970-01-01
  • 2018-11-03
相关资源
最近更新 更多