[英]python import file path relative inside a import module / use module without installing
如何導入模塊並像安裝它一樣使用它而不實際安裝它? 更具體地說,當我對已安裝的模塊進行導入時,所有導入都與模塊相關。 但是,當我只是導入它時,所有導入都與調用它的模塊相關。
作為一個具體的例子,在下面我希望run_import.py
打印module
not parent
。 但是因為它從父模塊而不是模塊導入cfg
,所以它打印了錯誤的。 我希望能夠在獨立的基礎上運行module1
並將其與任何調用它的代碼隔離開來,就像在安裝的 package 中一樣。
目錄結構是
module1/
__init__.py
cfg.py
tasks.py
run_module.py
utils.py
cfg.py
run_import.py
utils.py
代碼
# cfg.py
level = 'parent'
# module1/cfg.py
level='module'
# module1/tasks.py
import cfg
def run_it():
print(cfg.level)
# module1/run_module.py
import tasks
tasks.run_it() # prints 'module'
# module1/utils.py
def util_fun():
print('util module')
# utils.py
def util_fun():
print('util parent')
# run_import.py
import module1.tasks as tasks
tasks.run_it() # prints 'parent', would like it to print 'module'
import utils
utils.util_fun() # prints util parent, should not print util module
這給了我我一直在尋找的東西,但意外的結果是所有東西都相對於該模塊被導入
import sys
sys.path.insert(0, "module1")
tasks.run_it() # prints 'parent'
import utils
utils.util_fun() # prints util module, not util parent
這是我看過的幾個答案,他們似乎沒有解決它。
Python 中的“__package__”屬性的用途是什么? 這聽起來像是需要的,但不確定如何設置
Python3 importlib.util.spec_from_file_location 與相對路徑? 看起來很有希望,但我不確定如何使用它,特別是不確定文件路徑應該是什么
當您執行run_import.py
時,導入正在根文件夾( module1/
)中搜索。
所以你可以嘗試改變module1/tasks.py
from module1 import cfg
def run_it():
print(cfg.level)
試試這個,如果您只想更改run_import.py
,則將模塊添加到路徑中
import sys
sys.path.insert(0, "module1")
from module1 import tasks
tasks.run_it()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.