Python包导入详解:cookFish示例

0 下载量 100 浏览量 更新于2024-08-30 收藏 73KB PDF 举报
在Python编程中,`import`关键字起着至关重要的作用,它用于引入并加载外部模块或包中的功能到当前执行的程序中。在本文档中,我们通过一个具体的例子来深入理解如何使用`import`操作,以及它在包和模块管理中的应用。 首先,我们创建了一个名为`cookFish`的包,这是为了组织和管理与烹饪鱼类菜肴相关的代码。在这个包结构中,有两个关键文件:`__init__.py`和`cookBook.py`。`__init__.py`文件是Python包的标志,即使它可能为空,但它的存在表示该目录是一个包。而`cookBook.py`包含了实际的烹饪函数,例如`cookBook_hello()`。 在`__init__.py`中,定义了两个变量:`__version__`和`__author__`,以及一个名为`cookFish_hello()`的函数,用于显示包的名称和初始化信息。当导入包时,这些内容会被自动加载到命名空间中。 当我们尝试通过`import cookFish`语句导入这个包时,Python解释器会查找`cookFish`模块或包,并加载其中的内容。如果当前工作目录没有设置为`cookFish`的父目录,可能会出现`ModuleNotFoundError`,提示找不到指定的模块。解决这个问题的方法是使用`os`模块的`chdir()`函数更改当前工作目录。 通过`dir()`函数,我们可以检查当前的命名空间以及导入后的`cookFish`命名空间,看看哪些函数和变量被加载进来。这有助于调试和理解导入过程的效果。 这个实例展示了Python中基础的包和模块管理,包括如何创建、导入、以及检查包的内容。在大型项目中,包的使用可以帮助保持代码结构清晰,提高代码复用性和可维护性。了解`import`的正确使用方法对于编写高效、模块化的Python代码至关重要。

ImportError: dlopen(/Users/red/Library/Python/3.9/lib/python/site-packages/_cffi_backend.cpython-39-darwin.so, 0x0002): tried: '/Users/red/Library/Python/3.9/lib/python/site-packages/_cffi_backend.cpython-39-darwin.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/System/Volumes/Preboot/Cryptexes/OS/Users/red/Library/Python/3.9/lib/python/site-packages/_cffi_backend.cpython-39-darwin.so' (no such file), '/Users/red/Library/Python/3.9/lib/python/site-packages/_cffi_backend.cpython-39-darwin.so' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64'))thread '<unnamed>' panicked at 'Python API call failed', /Users/runner/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pyo3-0.18.3/src/err/mod.rs:790:5note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceTraceback (most recent call last): File "/usr/local/project/red/python/memory.py", line 3, in <module> import paramiko File "/Users/red/Library/Python/3.9/lib/python/site-packages/paramiko/__init__.py", line 22, in <module> from paramiko.transport import ( File "/Users/red/Library/Python/3.9/lib/python/site-packages/paramiko/transport.py", line 33, in <module> from cryptography.hazmat.primitives.ciphers import algorithms, Cipher, modes File "/Users/red/Library/Python/3.9/lib/python/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py", line 11, in <module> from cryptography.hazmat.primitives.ciphers.base import ( File "/Users/red/Library/Python/3.9/lib/python/site-packages/cryptography/hazmat/primitives/ciphers/base.py", line 10, in <module> from cryptography.exceptions import ( File "/Users/red/Library/Python/3.9/lib/python/site-packages/cryptography/exceptions.py", line 9, in <module> from cryptography.hazmat.bindings._rust import exceptions as rust_exceptionspyo3_runtime.PanicException: Python API call failed

2023-07-08 上传