全面解析python當(dāng)前路徑和導(dǎo)包路徑問題
引言
module:一個(gè) .py 文件就是個(gè) module
lib:抽象概念,和另外兩個(gè)不是一類,只要你喜歡,什么都是 lib,就算只有個(gè) hello world
package:就是個(gè)帶 __init__.py 的文件夾,并不在乎里面有什么,不過一般來講會(huì)包含一些 packages/modules
如何你有以下的疑問的話,那這個(gè)文章很適合你!
- 子疑問:為什么在 pycharm 中運(yùn)行單元測試是正常的?但還是在終端運(yùn)行就出現(xiàn)了導(dǎo)包錯(cuò)誤?
- 子疑問:Pycharm 中運(yùn)行正常,但是終端運(yùn)行出現(xiàn)錯(cuò)誤:
ModuleNotFoundError: No module named - 子疑問:為什么 python 在 vscode 運(yùn)行的路徑和 pycharm 不一致
- 子疑問:VSCode找不到相對路徑文件
何為當(dāng)前路徑?
所謂的當(dāng)前路徑到底是輸入命令的路徑還是 py 腳本文件所在的路徑?
插一句: Linux 等系統(tǒng)中查看當(dāng)前路徑的命令是 pwd, python 中查看當(dāng)前路徑是 os.getcwd()
? 疑問一 ????:python 程序的當(dāng)前路徑是執(zhí)行 python 腳本等路徑還是 python 腳本說在的路徑?
即執(zhí)行下面的命令的時(shí)候,所謂的當(dāng)前路徑是 testing 文件夾所在的路徑還是 main.py 文件所在路徑。
python testing/main.py
? 答案:當(dāng)前路徑是輸入運(yùn)行命令的路徑,而不是 py 文件所在的路徑。
對于??下面的命令,是無所謂區(qū)分這兩個(gè)路徑的,但是??上面的路徑就不一樣了
python main.py
導(dǎo)包路徑和當(dāng)前路徑的關(guān)系?
知道這個(gè)知識對寫程序避坑有什么幫助?,接下往下看吧!
? 疑問二 ????:如何查看 Python 的導(dǎo)包路徑?
- 子疑問:python 的導(dǎo)包順序是什么?
- 子疑問:python 導(dǎo)包的時(shí)候會(huì)去哪些文件夾下查找 package?
- 子疑問:python 導(dǎo)包的時(shí)候會(huì)去哪些路徑下查找 package?
我在 /Users/bot/Desktop/code/ideaboom 新建一個(gè)名為 testing 的文件夾,并在 testing 文件夾下新建一個(gè) main.py 的文件。
main.py 文件的內(nèi)容如下所示:
import os
import sys
print('當(dāng)前工作路徑: ', os.getcwd())
print('導(dǎo)包路徑為: ')
for p in sys.path:
print(p)并在 /Users/bot/Desktop/code/ideaboom 處運(yùn)行命令:python testing/main.py
程序輸出如下:
當(dāng)前工作路徑: /Users/bot/Desktop/code/ideaboom
導(dǎo)包路徑為:
/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
- 現(xiàn)象一 ??:我們可以看到 導(dǎo)包路徑 有好多,
sys.path返回的是一個(gè)列表對象,搜包的時(shí)候,會(huì)先從列表的第一個(gè)元素開始早起,比如import django就會(huì)先去/Users/bot/Desktop/code/ideaboom/testing查看有沒有叫做django的包或者django.py文件。再去/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip等依次查找。
python 中的包就是包含 __init__.py 文件的文件夾
- 現(xiàn)象二 ??:可以看到,當(dāng)前路徑是執(zhí)行
python testing/main.py命令的路徑,但是導(dǎo)包路徑就不是用執(zhí)行命令的路徑,而是main.py文件所在的路徑。 - 現(xiàn)象三 ??:sys.path 排第一的是
main.py文件所在的路徑。系統(tǒng)路徑都往后稍稍。
首要導(dǎo)包路徑不是當(dāng)前路徑有什么問題?
這是一個(gè)很典型的問題,我們往往會(huì)在項(xiàng)目的根目錄下面建一個(gè) testing 文件夾,把需要單元測試相關(guān)的文件放在。
但是當(dāng)我們輸入命令 python testing/main.py 的時(shí)候,就會(huì)出現(xiàn) ModuleNotFoundError: No module named xxx ,出現(xiàn)的原因就是上面提到的:首要導(dǎo)包路徑不是當(dāng)前路徑
本來 xxx 和 testing 文件夾是在項(xiàng)目的根目錄下面,sys.path 中的首要導(dǎo)包路徑就是項(xiàng)目的根目錄,但是當(dāng)我們 python testing/main.py 的時(shí)候,首要導(dǎo)包路變成了 testing 而不是項(xiàng)目根目錄了!這還是 main.py 中的 import xxx 當(dāng)然找不到了。
知道了問題如何解決呢?
解決什么???當(dāng)然是運(yùn)行 tetsing 文件夾下面的 main.py 文件報(bào)錯(cuò) ModuleNotFoundError: No module named xxx 的問題。??
? 疑問三:如何改變 Python 程序的首要導(dǎo)包路徑?
python 首要導(dǎo)包路徑就是 sys.path 列表中的第一個(gè)元素,即被運(yùn)行的 py 文件所在的文件夾路徑
方案一:動(dòng)態(tài)修改 sys.path
最常見的方式就是:
把當(dāng)前路徑添加到 sys.path 中,且為了避免命名沖突,最好添加到列表的頭部,而不是用 append 添加到尾部。至于本來的(不期望的)首要導(dǎo)包路徑 /Users/bot/Desktop/code/ideaboom/testing 可以刪除,也可以保留。
import os
import sys
print('當(dāng)前工作路徑: ', os.getcwd())
print('導(dǎo)包路徑為: ')
sys.path.insert(0,os.getcwd()) # 把當(dāng)前路徑添加到 sys.path 中
for p in sys.path:
print(p)程序輸出:??
當(dāng)前工作路徑: /Users/bot/Desktop/code/ideaboom
導(dǎo)包路徑為:
/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
但是這個(gè)方案不太好,有一些缺點(diǎn),比如下面的代碼,看起來就很不優(yōu)雅,因?yàn)榘凑?python 的代碼規(guī)范,導(dǎo)包相關(guān)的代碼應(yīng)該寫在最前面,這種 導(dǎo)包+代碼+導(dǎo)包 的方式破壞了 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()
方案二:使用環(huán)境變量 PYTHONPATH
?? 更好的方案 ??
因?yàn)槭滓獙?dǎo)包路徑的設(shè)定是 python 解釋器的默認(rèn)執(zhí)行,那我們能不能在 python 解釋器啟動(dòng)之前就指定好我們需要的首要導(dǎo)包路徑呢?
通過查看 python --help 命令,我們可以到以下內(nèi)容:??
usage: /opt/homebrew/Cellar/python@3.8/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 <prefix> directory (or <prefix>:<exec_prefix>).
The default module search path uses <prefix>/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.看了一圈下來,感覺這個(gè) PYTHONHOME 是救星,但實(shí)際上不是哦,恰恰是那個(gè)不起眼的 PYTHONPATH
testing/main.py
import os
import sys
print('當(dāng)前工作路徑: ', os.getcwd())
print('導(dǎo)包路徑為: ')
for p in sys.path:
print(p)我們可以使用下面的方式來啟動(dòng)程序:??
PYTHONPATH=$(pwd) python testing/main.py
此時(shí)程序的輸出變成了:??
(ideaboom) ╭─bot@mbp13m1.local ~/Desktop/code/ideaboom ‹master*›
╰─? PYTHONPATH=$(pwd) python testing/main.py
當(dāng)前工作路徑: /Users/bot/Desktop/code/ideaboom
導(dǎo)包路徑為:
/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) 的環(huán)境變量的作用域僅限于本次命令的運(yùn)行,不會(huì)擴(kuò)散到當(dāng)前的 shell 環(huán)境中。
以上就是全面解析python當(dāng)前路徑和導(dǎo)包路徑問題的詳細(xì)內(nèi)容,更多關(guān)于python當(dāng)前路徑導(dǎo)包路徑的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python利用matplotlib做圖中圖及次坐標(biāo)軸的實(shí)例
今天小編就為大家分享一篇Python利用matplotlib做圖中圖及次坐標(biāo)軸的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
pytorch中Tensor.to(device)和model.to(device)的區(qū)別及說明
這篇文章主要介紹了pytorch中Tensor.to(device)和model.to(device)的區(qū)別及說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
Python3安裝模塊報(bào)錯(cuò)Microsoft Visual C++ 14.0 is required的解決方法
這篇文章主要介紹了Python3安裝模塊報(bào)錯(cuò)Microsoft Visual C++ 14.0 is required的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
通過python3實(shí)現(xiàn)投票功能代碼實(shí)例
這篇文章主要介紹了通過python3實(shí)現(xiàn)投票功能代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09

