全面解析python当前路径和导包路径问题
作者:ponponon 发布时间:2022-09-08 16:00:21
引言
python中的模块、库、包有什么区别?
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()
方案二:使用环境变量 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 环境中。
来源:https://segmentfault.com/a/1190000041131903
猜你喜欢
- 一. ADO.NET的定义ADO.NET来源于COM组件库ADO(即ActiveX Data Objects),是微软公司新一代.NET数据
- 首先我们利用NodeJs先构建一个基本的服务器。 index.js var requestHandler = require(".
- 一、概述现有一个wenda1.xlsx文件,内容如下:需要将faq记录合并为一行,效果如下:注意:faq记录,每一行用||来拼接。二、多行转
- 简介testify可以说是最流行的(从 GitHub star 数来看)Go 语言测试库了。testify提供了很多方便的函数帮助我们做as
- 一、享元模式享元,可理解为 Python 中的元类、最小粒度的类,系统中存在大量的相似对象时,可以选择享元模式提高资源利用率。享元具有两种状
- 简单四则运算语法树可视化前几天有一篇博客是关于四则运算和二叉树的,我是把四则运算用二叉树写出来(我是用的 JSON 的形式来存储和表达的),
- 如,现在需要判断命令行是否传了参数,即 os.Args[1] 是否存在如果使用下述的判断:package main import ( &qu
- 假设你需要允许在Hero管理页面上导入CSV数据。为此,您需要添加一个指向更改Hero列表页面的链接,点击这个链接会跳转到上传页面。你需要编
- 数据归一化是深度学习数据预处理中非常关键的步骤,可以起到统一量纲,防止小数据被吞噬的作用。一:归一化的概念归一化就是把所有数据都转化成[0,
- 将一个类的接口转换成客户希望的另外一个接口。使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。应用场景:希望复用一些现存的类,但是接
- 在上一篇Python接口自动化测试系列文章:Python接口自动化之浅析requests模块get请求,介绍了requests模块、get请
- 1.子查询概念 (1)就是在查询的where子句中的判断依据是另一个查询的结果,如此就构成了一个外部的查询和一个内部的查询,这个内部的查询就
- 官网下载就好, https://www.python.org/downloads/release/python-352/用installer
- 系统:ubuntu18.04 x64GitHub:https://github.com/xingjidemimi/DjangoAPI.git
- 怎样编制留言簿程序呢?留言簿程序并不难,有很多选择可以实现,如CGI程序等等。本文介绍怎样用JavaScript编制留言簿程序,下面是一个完
- 前言文章抄袭在互联网中普遍存在,很多博主都收受其烦。近几年随着互联网的发展,抄袭等不道德行为在互联网上愈演愈烈,甚至复制、黏贴后发布标原创屡
- Python是一门弱类型语言,很多从C/C++转过来的朋友起初不是很适应。比如,在声明一个函数时,不能指定参数的类型。用C做类比,那就是所有
- 本文实例讲述了Sanic框架安装与简单用法。分享给大家供大家参考,具体如下:Sanic是一个类似Flask的Python 3.5+ Web服
- 这一次将使用pymysql来进行一次对MySQL的增删改查的全部操作,相当于对前五次的总结:先查阅数据库:现在编写源码进行增删改查操作,源码
- 一、什么是sql注入呢? 所谓SQL注入,就是