python 當前路徑和導包路徑問題全解析

ponponon發表於2021-12-20
python中的模組、庫、包有什麼區別? - laike9m的回答 - 知乎
module:一個 .py 檔案就是個 module
lib:抽象概念,和另外兩個不是一類,只要你喜歡,什麼都是 lib,就算只有個 hello world
package:就是個帶 __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()

圖片.png

方案二:使用環境變數 PYTHONPATH

? 更好的方案 ?

因為首要導包路徑的設定是 python 直譯器的預設執行,那我們能不能在 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) 的環境變數的作用域僅限於本次命令的執行,不會擴散到當前的 shell 環境中。

相關文章