简体   繁体   English

如何从python中的包导入所有函数?

[英]How do I import all functions from a package in python?

I have a directory as such: 我有一个目录:

python_scripts/
     test.py
     simupy/
          __init__.py
          info.py
          blk.py

'blk.py' and 'info.py are modules that contains several functions, one of which is the function 'blk_func(para)'. 'blk.py'和'info.py是包含多个函数的模块,其中一个是函数'blk_func(para)'。

Within '__init__.py' I have included the following code: 在'__init__.py'中我包含以下代码:

import os
dir_path = os.path.dirname(os.path.realpath(__file__))

file_lst = os.listdir(dir_path)
filename_lst = list(filter(lambda x: x[-3:]=='.py', file_lst))
filename_lst = list(map(lambda x: x[:-3], filename_lst))
filename_lst.remove('__init__')

__all__ = filename_lst.copy()

I would like to access the function 'blk_func(para)', as well as all other functions inside the package, within 'test.py'. 我想在'test.py'中访问函数'blk_func(para)',以及包内的所有其他函数。 Thus I import the package by putting the following line of code in 'test.py': 因此,我通过在'test.py'中放入以下代码行来导入包:

from simupy import*

However, inorder to use the function, I still have to do the following: 但是,为了使用该功能,我仍然需要执行以下操作:

value = blk.blk_func(val_param)

How do I import the package simupy, such that I can directly access the function in 'test.py' by just calling the function name? 如何导入软件包simupy,这样我只需调用函数名即可直接访问'test.py'中的函数? ie

value = blk_func(val_para)

Pretty easy 满容易

__init__.py : __init__.py

from simupy.blk import *
from simupy.info import *

Btw, just my two cents but it looks like you want to import your package's functions in __init__.py but perform actions in __main__.py . 顺便说一句,只是我的两分钱,但看起来你想要在__init__.py导入你的包的功能,但是在__main__.py执行操作。

Like 喜欢

__init__.py : __init__.py

from simupy.blk import *
from simupy.info import *

__main__.py : __main__.py

from simupy import *

# your code
dir_path = ....

It's the most pythonic way to do. 这是最诡计多端的方式。 After that you will be able to: 之后,您将能够:

  • Run your script as a proper Python module: python -m simupy 将您的脚本作为正确的Python模块运行: python -m simupy
  • Use your module as library: import simupy; print(simupy.bar()) 使用您的模块作为库: import simupy; print(simupy.bar()) import simupy; print(simupy.bar())
  • Import only a specific package / function: from simupy.info import bar . 仅导入特定的包/功能: from simupy.info import bar

For me it's part of the beauty of Python.. 对我而言,它是Python之美的一部分..

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

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