如何从同一个包导入

2024-05-16 18:30:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Windows 10下使用Python 3Jupyter。你知道吗

我有两个模块:mod_mainmod_sub。我想将各种模块(在本例中,只有os)从mod_sub导入mod_main。对我有效的方法如下:

模式_主.py

from pathlib import Path # works with / for any OS
import sys
sys.path.append(str(Path('C:/MyApps/Python_Base')))
from dummypackage.mod_sub import *
#from dummypackage import mod_sub
def print_path():
    print(os.path.realpath(__file__))

模式_sub.py公司

import os
print('mod_sub is imported')

然后在C:\MyApps\Python_Base下的Jupyter笔记本上运行以下内容

from dummypackage import mod_main
import importlib
importlib.reload(mod_main)
mod_main.print_path()

现在,我有几个问题:

  1. 通配符的使用是discouraged,但是如果我使用from dummypackage import mod_sub,那么我将无法访问其他导入的modeule(os)。那么,这里的最佳做法是什么?你知道吗
  2. 有没有更好的方法从同一个包中导入模块?我如何将路径添加到父文件夹并从中导入包.模块看起来很难看。有没有更好的办法?你知道吗

Tags: 模块path方法frompyimportmodos