python 当前路径和导包路径问题全解析

您所在的位置:网站首页 python中sys添加路径 python 当前路径和导包路径问题全解析

python 当前路径和导包路径问题全解析

2023-04-01 19:29| 来源: 网络整理| 查看: 265

python中的模块、库、包有什么区别? - laike9m的回答 - 知乎 module:一个 .py 文件就是个 modulelib:抽象概念,和另外两个不是一类,只要你喜欢,什么都是 lib,就算只有个 hello worldpackage:就是个带 __init__.py 的文件夹,并不在乎里面有什么,不过一般来讲会包含一些 packages/modules

如何你有以下的疑问的话,那这个文章很适合你!

子疑问:为什么在 pycharm 中运行单元测试是正常的?但还是在终端运行就出现了导包错误?子疑问:Pycharm 中运行正常,但是终端运行出现错误:ModuleNotFoundError: No module named子疑问:为什么 python 在 vscode 运行的路径和 pycharm 不一致子疑问:VSCode找不到相对路径文件何为当前路径?所谓的当前路径到底是输入命令的路径还是 py 脚本文件所在的路径?插一句: Linux 等系统中查看当前路径的命令是 pwd, python 中查看当前路径是 os.getcwd()

❓ 疑问一 👉🏻:python 程序的当前路径是执行 python 脚本等路径还是 python 脚本说在的路径?

即执行下面的命令的时候,所谓的当前路径是 testing 文件夹所在的路径还是 main.py 文件所在路径。

python testing/main.py

✅ 答案:当前路径是输入运行命令的路径,而不是 py 文件所在的路径。

对于👇下面的命令,是无所谓区分这两个路径的,但是👆上面的路径就不一样了

python main.py导包路径和当前路径的关系?

知道这个知识对写程序避坑有什么帮助?,接下往下看吧!

❓ 疑问二 👉🏻:如何查看 Python 的导包路径?

子疑问:python 的导包顺序是什么?子疑问:python 导包的时候会去哪些文件夹下查找 package?子疑问:python 导包的时候会去哪些路径下查找 package?

我在 /Users/bot/Desktop/code/ideaboom 新建一个名为 testing 的文件夹,并在 testing 文件夹下新建一个 main.py 的文件。

main.py 文件的内容如下所示:

import os import sys print('当前工作路径: ', os.getcwd()) print('导包路径为: ') for p in sys.path: print(p)

并在 /Users/bot/Desktop/code/ideaboom 处运行命令:python testing/main.py

程序输出如下:

当前工作路径: /Users/bot/Desktop/code/ideaboom 导包路径为: /Users/bot/Desktop/code/ideaboom/testing /Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9 /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload /Users/bot/.local/share/virtualenvs/ideaboom-8ZWsq-JB/lib/python3.9/site-packages

现象一 👀:我们可以看到 导包路径 有好多,sys.path 返回的是一个列表对象,搜包的时候,会先从列表的第一个元素开始早起,比如 import django 就会先去 /Users/bot/Desktop/code/ideaboom/testing 查看有没有叫做 django 的包或者 django.py 文件。再去 /Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip 等依次查找。

python 中的包就是包含 __init__.py 文件的文件夹现象二 👀:可以看到,当前路径是执行 python testing/main.py 命令的路径,但是导包路径就不是用执行命令的路径,而是 main.py 文件所在的路径。现象三 👀:sys.path 排第一的是 main.py 文件所在的路径。系统路径都往后稍稍。首要导包路径不是当前路径有什么问题?

这是一个很典型的问题,我们往往会在项目的根目录下面建一个 testing 文件夹,把需要单元测试相关的文件放在。

但是当我们输入命令 python testing/main.py 的时候,就会出现 ModuleNotFoundError: No module named xxx ,出现的原因就是上面提到的:首要导包路径不是当前路径

本来 xxx 和 testing 文件夹是在项目的根目录下面,sys.path 中的首要导包路径就是项目的根目录,但是当我们 python testing/main.py 的时候,首要导包路变成了 testing 而不是项目根目录了!这还是 main.py 中的 import xxx 当然找不到了。

知道了问题如何解决呢?

解决什么😨?当然是运行 tetsing 文件夹下面的 main.py 文件报错 ModuleNotFoundError: No module named xxx 的问题。🤯

❓ 疑问三:如何改变 Python 程序的首要导包路径?

python 首要导包路径就是 sys.path 列表中的第一个元素,即被运行的 py 文件所在的文件夹路径方案一:动态修改 sys.path

最常见的方式就是:

把当前路径添加到 sys.path 中,且为了避免命名冲突,最好添加到列表的头部,而不是用 append 添加到尾部。至于本来的(不期望的)首要导包路径 /Users/bot/Desktop/code/ideaboom/testing 可以删除,也可以保留。

import os import sys print('当前工作路径: ', os.getcwd()) print('导包路径为: ') sys.path.insert(0,os.getcwd()) # 把当前路径添加到 sys.path 中 for p in sys.path: print(p)

程序输出:👇

当前工作路径: /Users/bot/Desktop/code/ideaboom 导包路径为: /Users/bot/Desktop/code/ideaboom /Users/bot/Desktop/code/ideaboom/testing /Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9 /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload /Users/bot/.local/share/virtualenvs/ideaboom-8ZWsq-JB/lib/python3.9/site-packages

但是这个方案不太好,有一些缺点,比如下面的代码,看起来就很不优雅,因为按照 python 的代码规范,导包相关的代码应该写在最前面,这种 导包+代码+导包 的方式破坏了 pythonic

import os import sys import time import schedule from pathlib import Path import os import sys import time import schedule from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent sys.path.insert(0, str(BASE_DIR)) import django django.setup()

方案二:使用环境变量 PYTHONPATH

🥳 更好的方案 👇

因为首要导包路径的设定是 python 解释器的默认执行,那我们能不能在 python 解释器启动之前就指定好我们需要的首要导包路径呢?

通过查看 python --help 命令,我们可以到以下内容:👇

usage: /opt/homebrew/Cellar/[email protected]/3.8.12/bin/python3 [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -b : issue warnings about str(bytes_instance), str(bytearray_instance) and comparing bytes/bytearray with str. (-bb: issue errors) -B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x -c cmd : program passed in as string (terminates option list) -d : debug output from parser; also PYTHONDEBUG=x -E : ignore PYTHON* environment variables (such as PYTHONPATH) -h : print this help message and exit (also --help) -i : inspect interactively after running script; forces a prompt even if stdin does not appear to be a terminal; also PYTHONINSPECT=x -I : isolate Python from the user's environment (implies -E and -s) -m mod : run library module as a script (terminates option list) -O : remove assert and __debug__-dependent statements; add .opt-1 before .pyc extension; also PYTHONOPTIMIZE=x -OO : do -O changes and also discard docstrings; add .opt-2 before .pyc extension -q : don't print version and copyright messages on interactive startup -s : don't add user site directory to sys.path; also PYTHONNOUSERSITE -S : don't imply 'import site' on initialization -u : force the stdout and stderr streams to be unbuffered; this option has no effect on stdin; also PYTHONUNBUFFERED=x -v : verbose (trace import statements); also PYTHONVERBOSE=x can be supplied multiple times to increase verbosity -V : print the Python version number and exit (also --version) when given twice, print more information about the build -W arg : warning control; arg is action:message:category:module:lineno also PYTHONWARNINGS=arg -x : skip first line of source, allowing use of non-Unix forms of #!cmd -X opt : set implementation-specific option. The following options are available: -X faulthandler: enable faulthandler -X showrefcount: output the total reference count and number of used memory blocks when the program finishes or after each statement in the interactive interpreter. This only works on debug builds -X tracemalloc: start tracing Python memory allocations using the tracemalloc module. By default, only the most recent frame is stored in a traceback of a trace. Use -X tracemalloc=NFRAME to start tracing with a traceback limit of NFRAME frames -X showalloccount: output the total count of allocated objects for each type when the program finishes. This only works when Python was built with COUNT_ALLOCS defined -X importtime: show how long each import takes. It shows module name, cumulative time (including nested imports) and self time (excluding nested imports). Note that its output may be broken in multi-threaded application. Typical usage is python3 -X importtime -c 'import asyncio' -X dev: enable CPython's "development mode", introducing additional runtime checks which are too expensive to be enabled by default. Effect of the developer mode: * Add default warning filter, as -W default * Install debug hooks on memory allocators: see the PyMem_SetupDebugHooks() C function * Enable the faulthandler module to dump the Python traceback on a crash * Enable asyncio debug mode * Set the dev_mode attribute of sys.flags to True * io.IOBase destructor logs close() exceptions -X utf8: enable UTF-8 mode for operating system interfaces, overriding the default locale-aware mode. -X utf8=0 explicitly disables UTF-8 mode (even when it would otherwise activate automatically) -X pycache_prefix=PATH: enable writing .pyc files to a parallel tree rooted at the given directory instead of to the code tree --check-hash-based-pycs always|default|never: control how Python invalidates hash-based .pyc files file : program read from script file - : program read from stdin (default; interactive mode if a tty) arg ...: arguments passed to program in sys.argv[1:] Other environment variables: PYTHONSTARTUP: file executed on interactive startup (no default) PYTHONPATH : ':'-separated list of directories prefixed to the default module search path. The result is sys.path. PYTHONHOME : alternate directory (or :). The default module search path uses /lib/pythonX.X. PYTHONCASEOK : ignore case in 'import' statements (Windows). PYTHONUTF8: if set to 1, enable the UTF-8 mode. PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr. PYTHONFAULTHANDLER: dump the Python traceback on fatal errors. PYTHONHASHSEED: if this variable is set to 'random', a random value is used to seed the hashes of str and bytes objects. It can also be set to an integer in the range [0,4294967295] to get hash values with a predictable seed. PYTHONMALLOC: set the Python memory allocators and/or install debug hooks on Python memory allocators. Use PYTHONMALLOC=debug to install debug hooks. PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of locale coercion and locale compatibility warnings on stderr. PYTHONBREAKPOINT: if this variable is set to 0, it disables the default debugger. It can be set to the callable of your debugger of choice. PYTHONDEVMODE: enable the development mode. PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files.

看了一圈下来,感觉这个 PYTHONHOME 是救星,但实际上不是哦,恰恰是那个不起眼的 PYTHONPATH

testing/main.py

import os import sys print('当前工作路径: ', os.getcwd()) print('导包路径为: ') for p in sys.path: print(p)

我们可以使用下面的方式来启动程序:👇

PYTHONPATH=$(pwd) python testing/main.py

此时程序的输出变成了:👇

(ideaboom) ╭─[email protected] ~/Desktop/code/ideaboom ‹master*› ╰─➤ PYTHONPATH=$(pwd) python testing/main.py 当前工作路径: /Users/bot/Desktop/code/ideaboom 导包路径为: /Users/bot/Desktop/code/ideaboom/testing /Users/bot/Desktop/code/ideaboom /Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9 /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload /Users/bot/.local/share/virtualenvs/ideaboom-8ZWsq-JB/lib/python3.9/site-packages

让我们再来看看 PYTHONPATH=$(pwd) python testing/main.py, 它等效于 PYTHONPATH=/Users/bot/Desktop/code/ideaboom python testing/main.py.

在 python testing/main.py 添加 PYTHONPATH=$(pwd) 的环境变量的作用域仅限于本次命令的运行,不会扩散到当前的 shell 环境中。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3