Prevent script dir from being added to sys.path in Python 3

 ̄綄美尐妖づ 提交于 2021-02-08 13:17:33

问题


Is there a way to prevent the script's directory from being added to sys.path in python3? I'm getting import conflicts due to the fact that imports are relative in python. A legacy project I'm working with has a file called logger.py in the root directory of the script which conflicts with the built-in logger.

The custom build system that I use ends up creating symlinks to all the files and dependencies and in production, at runtime we use the -E flag to ignore any system set PYTHONPATH and set the path to what we want. But running tests/scripts from PyCharm doesn't work because of this conflict.


回答1:


At the top of your script, you can try doing something like:

import os
import sys

# the first element of sys.path is an empty string, meant to represent the current directory
sys.path.remove('')

then do your normal imports.

Beware, this will cause all relative imports from your current directory to fail, potentially causing more problems than your legacy logger.py

With regards to your second question, whether or not there's anything that can be done to prevent the directory from being added to sys.path in the first place, the short answer is no. From the 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.


I suppose you could set up a symlink from your current working directory to another directory, keep your actual script there, and point the symlink at it. Also from the above docs (emphasis mine):

On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed.



来源:https://stackoverflow.com/questions/54621527/prevent-script-dir-from-being-added-to-sys-path-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!