python – 为什么sys.path不包含cwd()?

我在Linux OS下使用python3和emacs(编辑器和shell).为什么cwd不在sys.path中?我们怎么能把它,所有会议!
我谢谢你.

解决方法:

您不希望将cwd()添加到sys.path.总是添加cwd()会是一个糟糕的主意,因为你无法再控制哪些文件可以导入.

Python会添加正在执行的脚本的目录.

例如.当你跑:

python.exe path/to/script.py

然后path / to自动添加到sys.path中.

仅当您从当前目录运行脚本时才会将“添加到路径的开头”,这意味着将搜索当前工作目录的导入.例如.当您运行python.exe localfile.py时,Python会添加当前工作目录,假设您在导入时不会更改当前工作目录.

请参阅命令行和环境文档中的Interface options

If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path, and the file is executed as the __main__ module.

sys.path documentation

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

您始终可以显式地将当前工作目录添加到sys.path:

import sys

if sys.path[0] != '':
    sys.path.insert(0, '')

请注意,该工作目录中的任何python文件或包的名称与您在代码中已使用的模块相匹配,将掩盖该模块,很容易导致破坏.

上一篇:k8s - SVC(Service)


下一篇:Kubernetes(k8s)的Service资源