全面解析python當前路徑和導包路徑問題
引言
module:一個 .py 文件就是個 module
lib:抽象概念,和另外兩個不是一類,只要你喜歡,什么都是 lib,就算只有個 hello world
package:就是個帶 __init__.py 的文件夾,并不在乎里面有什么,不過一般來講會包含一些 packages/modules
如何你有以下的疑問的話,那這個文章很適合你!
- 子疑問:為什么在 pycharm 中運行單元測試是正常的?但還是在終端運行就出現(xiàn)了導包錯誤?
- 子疑問:Pycharm 中運行正常,但是終端運行出現(xiàn)錯誤:
ModuleNotFoundError: No module named
- 子疑問:為什么 python 在 vscode 運行的路徑和 pycharm 不一致
- 子疑問:VSCode找不到相對路徑文件
何為當前路徑?
所謂的當前路徑到底是輸入命令的路徑還是 py
腳本文件所在的路徑?
插一句: Linux
等系統(tǒng)中查看當前路徑的命令是 pwd
, python 中查看當前路徑是 os.getcwd()
? 疑問一 ????:python
程序的當前路徑是執(zhí)行 python
腳本等路徑還是 python
腳本說在的路徑?
即執(zhí)行下面的命令的時候,所謂的當前路徑是 testing
文件夾所在的路徑還是 main.py
文件所在路徑。
python testing/main.py
? 答案:當前路徑是輸入運行命令的路徑,而不是 py
文件所在的路徑。
對于??下面的命令,是無所謂區(qū)分這兩個路徑的,但是??上面的路徑就不一樣了
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
- 現(xiàn)象一 ??:我們可以看到 導包路徑 有好多,
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
文件的文件夾
- 現(xiàn)象二 ??:可以看到,當前路徑是執(zhí)行
python testing/main.py
命令的路徑,但是導包路徑就不是用執(zhí)行命令的路徑,而是main.py
文件所在的路徑。 - 現(xiàn)象三 ??:sys.path 排第一的是
main.py
文件所在的路徑。系統(tǒng)路徑都往后稍稍。
首要導包路徑不是當前路徑有什么問題?
這是一個很典型的問題,我們往往會在項目的根目錄下面建一個 testing 文件夾,把需要單元測試相關的文件放在。
但是當我們輸入命令 python testing/main.py
的時候,就會出現(xiàn) ModuleNotFoundError: No module named xxx
,出現(xiàn)的原因就是上面提到的:首要導包路徑不是當前路徑
本來 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 文件所在的文件夾路徑
方案一:動態(tài)修改 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
但是這個方案不太好,有一些缺點,比如下面的代碼,看起來就很不優(yōu)雅,因為按照 python 的代碼規(guī)范,導包相關的代碼應該寫在最前面,這種 導包+代碼+導包
的方式破壞了 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
?? 更好的方案 ??
因為首要導包路徑的設定是 python 解釋器的默認執(zhí)行,那我們能不能在 python 解釋器啟動之前就指定好我們需要的首要導包路徑呢?
通過查看 python --help 命令,我們可以到以下內容:??
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.
看了一圈下來,感覺這個 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) ╭─bot@mbp13m1.local ~/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)
的環(huán)境變量的作用域僅限于本次命令的運行,不會擴散到當前的 shell 環(huán)境中。
以上就是全面解析python當前路徑和導包路徑問題的詳細內容,更多關于python當前路徑導包路徑的資料請關注腳本之家其它相關文章!
相關文章
Python利用matplotlib做圖中圖及次坐標軸的實例
今天小編就為大家分享一篇Python利用matplotlib做圖中圖及次坐標軸的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07pytorch中Tensor.to(device)和model.to(device)的區(qū)別及說明
這篇文章主要介紹了pytorch中Tensor.to(device)和model.to(device)的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07Python3安裝模塊報錯Microsoft Visual C++ 14.0 is required的解決方法
這篇文章主要介紹了Python3安裝模塊報錯Microsoft Visual C++ 14.0 is required的解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07