【问题标题】:Python Module not found ONLY when .py file is on desktop仅当 .py 文件在桌面上时找不到 Python 模块
【发布时间】:2023-02-09 21:44:35
【问题描述】:

仅对于保存在我的桌面上的 .py 文件,由于模块内发生的导入未找到模块,导入某些模块(如 pandas)失败。 当文件保存到其他位置时,不会发生此行为。

在 Mac 上工作,我制作了一个 test.py 文件,它只包含:import pandas as pd

当此 test.py 保存在我的桌面上时,它会生成此错误:

Desktop % python3 test.py
Traceback (most recent call last):
  File "/Users/XXX/Desktop/test.py", line 2, in <module>
    import pandas as pd
  File "/Users/XXX/Desktop/pandas/__init__.py", line 22, in <module>
    from pandas.compat import (
  File "/Users/XXX/Desktop/pandas/compat/__init__.py", line 15, in <module>
    from pandas.compat.numpy import (
  File "/Users/XXX/Desktop/pandas/compat/numpy/__init__.py", line 7, in <module>
    from pandas.util.version import Version
  File "/Users/XXX/Desktop/pandas/util/__init__.py", line 1, in <module>
    from pandas.util._decorators import (  # noqa
  File "/Users/XXX/Desktop/pandas/util/_decorators.py", line 14, in <module>
    from pandas._libs.properties import cache_readonly  # noqa
  File "/Users/XXX/Desktop/pandas/_libs/__init__.py", line 13, in <module>
    from pandas._libs.interval import Interval
ModuleNotFoundError: No module named 'pandas._libs.interval'

奇怪的是,如果我将 test.py 文件保存到我 HD 上的任何其他位置,它会完美地导入 pandas。 其他一些模块也会发生同样的事情。我尝试导入的模块似乎没问题,但在模块内部发生的导入失败。

从桌面文件夹或任何其他文件夹在控制台中运行 which python3 会导致: /用户/XXXX/.pyenv/shims/python

python3 --version 导致所有位置的 Python 3.10.9。

【问题讨论】:

    标签: python macos python-3.10 modulenotfounderror file-location


    【解决方案1】:

    您的桌面上有一个名为 pandas 的目录。

    Python 尝试从此目录而不是名为pandas 的全局包导入。

    也可以看到异常中,看trace,代码从/Users/XXX/Desktop/test.py移动到/Users/XXX/Desktop/pandas/__init__.py等等。

    只需重命名桌面上的目录名称即可。 为了您自己的安全,您不应保存与全局包同名的目录。

    【讨论】:

      【解决方案2】:

      该问题可能与桌面文件夹权限有关,请检查此

      https://support.apple.com/en-gb/guide/mac-help/mchld5a35146/mac

      从文章

      Choose Apple menu  > System Settings, then click Privacy & Security in the sidebar. (You may need to scroll down.)
      
      Click Files and Folders.
      
      For each app in the list, turn the ability to access files and folders in specific locations on or off.
      

      您应该能够选择桌面文件夹的权限,如此例所示

      【讨论】: