最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

全面解析python當(dāng)前路徑和導(dǎo)包路徑問題

 更新時(shí)間:2023年05月16日 10:49:13   作者:ponponon  
這篇文章主要為大家介紹了python當(dāng)前路徑和導(dǎo)包路徑問題的全面解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

引言

python中的模塊、庫、包有什么區(qū)別?

module:一個(gè) .py 文件就是個(gè) module

lib:抽象概念,和另外兩個(gè)不是一類,只要你喜歡,什么都是 lib,就算只有個(gè) hello world

package:就是個(gè)帶 __init__.py 的文件夾,并不在乎里面有什么,不過一般來講會(huì)包含一些 packages/modules

如何你有以下的疑問的話,那這個(gè)文章很適合你!

  • 子疑問:為什么在 pycharm 中運(yùn)行單元測(cè)試是正常的?但還是在終端運(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找不到相對(duì)路徑文件

何為當(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 文件所在的路徑。

對(duì)于??下面的命令,是無所謂區(qū)分這兩個(gè)路徑的,但是??上面的路徑就不一樣了

python main.py

導(dǎo)包路徑和當(dāng)前路徑的關(guān)系?

知道這個(gè)知識(shí)對(duì)寫程序避坑有什么幫助?,接下往下看吧!

疑問二 ????:如何查看 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è)列表對(duì)象,搜包的時(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 文件夾,把需要單元測(cè)試相關(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

讓我們?cè)賮砜纯?nbsp;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)包路徑的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python爬蟲parsel-css選擇器的具體用法

    python爬蟲parsel-css選擇器的具體用法

    本文主要介紹了python爬蟲parsel-css選擇器的具體用法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • 利用python獲取想要搜索的數(shù)據(jù)

    利用python獲取想要搜索的數(shù)據(jù)

    這篇文章主要介紹了利用Python爬蟲采集想要搜索的信息(利用某du的接口實(shí)現(xiàn))并且處理掉它的反爬手段,文中示例代碼很詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴快來一起學(xué)習(xí)吧
    2023-05-05
  • python數(shù)據(jù)分析工具之 matplotlib詳解

    python數(shù)據(jù)分析工具之 matplotlib詳解

    對(duì)于 Python 來說,matplotlib 是最著名的繪圖庫,它主要用于二維繪圖,當(dāng)然也可以進(jìn)行簡(jiǎn)單的三維繪圖。這篇文章主要介紹了python數(shù)據(jù)分析工具之 matplotlib的相關(guān)知識(shí),需要的朋友可以參考下
    2020-04-04
  • python監(jiān)控進(jìn)程腳本

    python監(jiān)控進(jìn)程腳本

    這篇文章主要為大家詳細(xì)介紹了python監(jiān)控進(jìn)程腳本,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • Python使用DeepSeek進(jìn)行聯(lián)網(wǎng)搜索功能詳解

    Python使用DeepSeek進(jìn)行聯(lián)網(wǎng)搜索功能詳解

    Python作為一種非常流行的編程語言,結(jié)合DeepSeek這一高性能的深度學(xué)習(xí)工具包,可以方便地處理各種深度學(xué)習(xí)任務(wù),本文將介紹一下如何使用Python和DeepSeek進(jìn)行聯(lián)網(wǎng)搜索,感興趣是可以了解下
    2025-03-03
  • Python+OpenCV之圖像輪廓詳解

    Python+OpenCV之圖像輪廓詳解

    這篇文章主要為大家詳細(xì)介紹了Python?OpenCV實(shí)現(xiàn)圖像輪廓的方法,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的可以了解一下
    2022-09-09
  • 深入了解python的tkinter實(shí)現(xiàn)簡(jiǎn)單登錄

    深入了解python的tkinter實(shí)現(xiàn)簡(jiǎn)單登錄

    這篇文章主要為大家介紹了python的tkinter實(shí)現(xiàn)簡(jiǎn)單登錄,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-12-12
  • python中requests庫session對(duì)象的妙用詳解

    python中requests庫session對(duì)象的妙用詳解

    這篇文章主要介紹了python中requests庫session對(duì)象的妙用詳解,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-10-10
  • python實(shí)現(xiàn)新年倒計(jì)時(shí)實(shí)例代碼

    python實(shí)現(xiàn)新年倒計(jì)時(shí)實(shí)例代碼

    大家好,本篇文章主要講的是python實(shí)現(xiàn)新年倒計(jì)時(shí)實(shí)例代碼,昂星期的同學(xué)趕快來看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • 使用Python實(shí)現(xiàn)ELT統(tǒng)計(jì)多個(gè)服務(wù)器下所有數(shù)據(jù)表信息

    使用Python實(shí)現(xiàn)ELT統(tǒng)計(jì)多個(gè)服務(wù)器下所有數(shù)據(jù)表信息

    這篇文章主要介紹了使用Python實(shí)現(xiàn)ELT統(tǒng)計(jì)多個(gè)服務(wù)器下所有數(shù)據(jù)表信息,ETL,是英文Extract-Transform-Load的縮寫,用來描述將數(shù)據(jù)從來源端經(jīng)過抽取(extract)、轉(zhuǎn)換(transform)、加載(load)至目的端的過程,需要的朋友可以參考下
    2023-07-07

最新評(píng)論

张家港市| 通榆县| 永福县| 义马市| 新宾| 重庆市| 金阳县| 阿巴嘎旗| 盈江县| 阿荣旗| 武鸣县| 渭源县| 兴安盟| 萨迦县| 武夷山市| 五家渠市| 玉树县| 日土县| 阳江市| 益阳市| 阳新县| 达日县| 右玉县| 兰考县| 唐河县| 湄潭县| 石楼县| 溆浦县| 湖北省| 江永县| 思茅市| 卢龙县| 台北县| 西乡县| 大足县| 西峡县| 缙云县| 和平区| 朝阳县| 崇礼县| 道孚县|