簡體   English   中英

Python 包內引用不起作用

[英]Python intra-package references not working

我正在努力使用包內引用。 這是我正在關注的文檔https://docs.python.org/3.9/tutorial/modules.html#intra-package-references

我正在做一個小測試:

test/
    __init__.py
    module_a/
        __init__.py
        script_a.py
            ( from test.module_b import script_b )
    module_b/
        __init__.py
        script_b.py
            ( def something(): print("something") )
    

但是我的導入不起作用,並且出現了這個錯誤

Exception has occurred: ModuleNotFoundError
No module named 'test'
File "/Users/nacho/Desktop/test/module_a/script_a.py", line 1, in <module>
from test.module_b import script_b

我究竟做錯了什么?

我沒有使用任何框架。 使用此命令只需簡單的 python 3.9

python3 script_a.py

我沒有安裝測試 package o 使用 -m 開關。

問候!

它不起作用,因為在 Python 的import paths上找不到 package test 你有(至少)四個選項來解決這個問題:

  1. 包含test目錄的目錄運行腳本,即python test/module_a/script_a.py 這樣,在test package 中使用的所有導入都必須是絕對的,即形式from test.module_b import script_b (而不是from..module_b import script_b )。
  2. 通過-m開關運行 package ,同樣從包含test目錄的目錄: python -m test.module_a 您需要在module_a中提供一個額外的__main__.py文件來調用所需的功能。 這樣你也可以使用相對導入,即. ..
  3. 安裝整個 package ,然后您可以從任何地方從命令行運行它(使用(2)中描述的步驟)。
  4. 修改PYTHONPATH指向包含test的目錄: PYTHONPATH=/path/to/test python script_a.py

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM