包(package)跟目录的区别

image.png
python包中都有一个 init.py 文件

在编写python 代码的时候,如果有包的导入,也就是使用 from … import … 导入自己编写的代码时。在创建的时候一定要使用包的方式创建,也就是说在文件夹下一定要有 init.py 文件。


如下代码
分别位于 config, testcase 目录下
config/res.py

  1. url = "http://47.100.175.62:3000"

testcases/test_demo.py

  1. from config.res import url
  2. def test_url():
  3. assert url == "http://47.100.175.62:3000"

使用pytest 命令执行。会报 没有config 模块的错误。
image.png
在Python中,如果在别的python文件中引用另外的python文件中定义的代码,需要声明为包。


分别在config ,testcases 目录下创建空的文件,但是文件名一定要为 init.py
image.png
创建好之后,再次运行 就可以了。
image.png