【问题标题】:python import file path relative inside a import module / use module without installingpython导入文件路径相对于导入模块/使用模块而不安装
【发布时间】:2021-06-06 04:23:11
【问题描述】:

如何导入模块并像安装它一样使用它而不实际安装它?更具体地说,当我对已安装的模块进行导入时,所有导入都与模块相关。但是,当我只是导入它时,所有导入都与调用它的模块相关。

作为一个具体的例子,在下面我希望run_import.py 打印module 而不是parent。但是因为它从父模块而不是模块导入cfg,所以它打印了错误的。我希望能够独立运行module1,并将其与任何调用它的代码隔离开来,就像在已安装的包中一样。

目录结构是


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

这是我看过的几个答案,他们似乎没有解决它。

What's the purpose of the "__package__" attribute in Python? 这听起来像是需要的,但不确定如何设置

Python3 importlib.util.spec_from_file_location with relative path? 看起来很有希望,但我不确定如何使用它,尤其是不确定文件路径应该是什么

How to use a packed python package without installing it

Import a module from a relative path

Can a python module be imported without installing

Import module using relative paths

【问题讨论】:

    标签: python


    【解决方案1】:

    当您执行 run_import.py 时,导入正在根文件夹 (module1/) 中搜索。

    所以你可以尝试更改module1/tasks.py

    from module1 import cfg
    
    def run_it():
        print(cfg.level)
    

    【讨论】:

    • 可以,但我希望能够独立运行module1,并将其与任何调用它的代码隔离开来,就像在已安装的包中一样。
    • 这是python世界的一个已知问题,如果你运行一个python文件,它不能在它上面导入模块。一种解决方法是将所有主要/可执行文件保留在项目的顶层,并为 utils/test 文件创建子文件夹。见这里:patricksoftwareblog.com/structure-of-a-python-project
    【解决方案2】:

    试试这个,如果您只想更改run_import.py,则将模块添加到路径中有效

    import sys
    sys.path.insert(0, "module1")
    
    from module1 import tasks
    tasks.run_it()
    
    

    【讨论】:

    • 这可行,但会产生意想不到的后果,即现在所有内容都相对于该模块被导入,请参阅更新后的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多