有没有办法阻止脚本的目录被添加到 python3 中的 sys.path?由于导入在 python 中是相对的,因此我遇到了导入冲突。我正在处理的一个遗留项目在脚本的根目录中有一个名为 logger.py
的文件,它与内置的 logger
冲突。
我使用的自定义构建系统最终创建了所有文件和依赖项的符号链接(symbolic link),在生产中,在运行时我们使用 -E
标志来忽略任何系统集 PYTHONPATH
并将路径设置为我们想要的。但由于此冲突,无法从 PyCharm 运行测试/脚本。
最佳答案
在脚本的顶部,您可以尝试执行以下操作:
import os
import sys
# the first element of sys.path is an empty string, meant to represent the current directory
sys.path.remove('')
然后进行正常的导入。
当心,这将导致从您当前目录的所有 相关导入失败,可能导致比您的遗留 logger.py
关于您的第二个问题,是否可以采取任何措施来防止目录首先被添加到 sys.path
,简短的回答是否定的。来自Python 3 docs on "module search path" :
sys.path is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- The installation-dependent default.
我想您可以设置一个从当前工作目录到另一个目录的符号链接(symbolic link),将您的实际脚本放在那里,然后将符号链接(symbolic link)指向它。同样来自上述文档(强调我的):
On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed.
关于python - 防止将脚本目录添加到 Python 3 中的 sys.path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54621527/