Python 导入多个脚本

Python importing multiple scripts

我一直在研究 python 需要导入多个库的脚本。

目前我的目录结构是

program/
    main.py
    libs/
        __init__.py
        dbconnect.py
        library01.py
        library02.py
        library03.py

我的dbconnect.py里面有以下内容

import psycopg2

class dbconnect:

    def __init__(self):
        self.var_parameters = "host='localhost' dbname='devdb' user='temp' password='temp'"

    def pgsql(self):
        try:
            var_pgsqlConn = psycopg2.connect(self.var_parameters)
        except:
            print("connection failed")

    return var_pgsqlConn

我可以使用

在我的 main.py 中导入和使用它
from libs.dbconnect import dbconnect

class_dbconnect = dbconnect()
var_pgsqlConn = class_dbconnect.pgsql()

这按预期工作,但是我正在尝试导入所有库脚本,每个脚本的内容都与下面相似

def library01():
    print("empty for now but this is library 01")

我已经添加到我的 __init__.py 脚本中

__all__ = ["library01", "library02"]

然后在我的 main.py 中,我尝试导入并使用它们,如下所示

from libs import *

library01()

我收到以下错误

TypeError: 'module' object is not callable

我假设您的 library0x.py 中的内容不同(functions/class 的名称不同)

最好的方法是将所有子文件内容导入 __init__.py

# __init__.py
from .dbconnect import *
from .library01 import *
from .library02 import *
from .library03 import *

那么你可以使用下面的方法:

from libs import library01, library02

如果由于某些原因你想在你的 library0x.py 文件中限制使用通配符 (*) 的输入,你可以定义一个包含所有函数名称的 __all__ 变量您将使用通配符导入:

# library01.py

__all__ = ["library01"]

def a_local_function():
    print "Local !"

def library01():
    print "My library function"

然后,通过from .library01 import *,只会导入函数library01


编辑:也许我误解了这个问题:这里有一些方法可以在文件 library01.py 中导入函数 library01 :

# Example 1:
from libs.library01 import library01
library01()

# Example 2:
import libs.library01
libs.library01.library01()

# Example 3:
import libs.library01 as library01
library01.library01()

在您的例子中,library01 是一个 模块 ,其中包含一个名为 library01 函数 。您导入 library01 模块并尝试将其作为函数调用。那就是问题所在。您应该这样调用该函数:

library01.library01()