简体   繁体   English

子包中的Python包/模块导入功能

[英]Python package/module import functions from sub packages

I'm building a python package to do some auditing of systems at work. 我正在构建一个python软件包,以对工作中的系统进行一些审核。 Thus far I've been able to work with using free floating .py files and and running the main file in the same directory as the module files. 到目前为止,我已经能够使用免费的浮动.py文件并在与模块文件相同的目录中运行主文件。 At a high level I want to create a package that holds several subpackages for specific audits. 在较高的层次上,我想创建一个包,其中包含用于特定审核的多个子包。 bigpackage>subpackage>modulefile.py I want to be able to import specific functions/methods from the modulefile. bigpackage> subpackage> modulefile.py我希望能够从modulefile导入特定的功能/方法。 How can I accomplish this? 我该怎么做?
I have the __init__ files in place for all my packages and can access them with the usual from bigpackage import modulefile and run them using the dot operator like modulefile.function1(bla, bla, bla) I would like to be able to import specific functions directly so I can run without using the dot operator like function1(bla, bla, bla) . 我已经为所有程序包准备了__init__文件,并且可以通过from bigpackage import modulefile的常规文件来访问它们,并可以使用点运算符(例如modulefile.function1(bla, bla, bla)运行它们modulefile.function1(bla, bla, bla)我希望能够导入特定的功能直接运行,因此无需使用像function1(bla, bla, bla)这样的点运算符就可以运行。

from bigpackage.subpackage.modulefile import function1, function2

function1(bla, bla, bla)

From: How to import a module given the full path? 来自: 如何在给定完整路径的情况下导入模块?

my directory layout: 我的目录布局:

/my_package
    /__init__.py
    /testfile.py
    /my_module
        /__init__.py

method 1: 方法1:

import imp
my_module = imp.load_sourc('my_module','.my_module/__init__.py')
my_module.function1()

or for restricted importing: 或用于受限进口:

import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from my_module import function1
function1()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM