繁体   English   中英

将 function 变量传递给另一个文件 python

[英]passing function variables to another file python

我需要将 data_connection 传递到我的 main.py 引擎中,因为该变量是存储来自 mysql 字符串的数据的地方。 在 main.py 中它说参数 data_connection 未填充但我只能输入 'data_connection=' 我很困惑我应该做什么......

加载文件.py

def get_connection():
        cursor = connection.cursor()
        cursor.execute(
            "SELECT ID, Type, Server, Port, User, Password, isActive, FileExtension, FileContains, FileLocation, "
        "ScheduleMinutes, IntervalTime from DataConnection WHERE isActive=True")
    
        data_connection = cursor.fetchall()

def download_files(data_connection):

        for data_connection_detail in data_connection:
            # type email will be IMAP, POP3, or FTP
            connection_type = data_connection_detail[1]

            # create data_source object
            if connection_type == 'IMAP':
                ez_email.read_email_imap(data_connection_detail)

            elif connection_type == 'POP3':
                ez_email.read_email_pop3(data_connection_detail)

            elif connection_type == 'FTP':
                ez_ftp.easy_ftp(data_connection_detail)

主程序

from load_file import get_connection
from load_file import download_files

def run_engine():
    while True:
        get_connection()
        download_files()



if __name__ == "__main__":
    run_engine()

data_connection是 load_file.py 中的局部变量,在 function 退出时被销毁。 您在 download_files 中也有一个类似名称的参数。 这是在每次调用 function 时创建的两个不同的唯一变量。它们恰好具有相同的名称,但在不同的命名空间中,因此不要引用相同的东西。

这种情况下的解决方案是从第一个 function 返回 object 并将其用作第二个中的参数。

加载文件.py

def get_connection():
        cursor = connection.cursor()
        cursor.execute(
            "SELECT ID, Type, Server, Port, User, Password, isActive, FileExtension, FileContains, FileLocation, "
        "ScheduleMinutes, IntervalTime from DataConnection WHERE isActive=True")
    
        return cursor.fetchall()

def download_files(data_connection):

        for data_connection_detail in data_connection:
            # type email will be IMAP, POP3, or FTP
            connection_type = data_connection_detail[1]

            # create data_source object
            if connection_type == 'IMAP':
                ez_email.read_email_imap(data_connection_detail)

            elif connection_type == 'POP3':
                ez_email.read_email_pop3(data_connection_detail)

            elif connection_type == 'FTP':
                ez_ftp.easy_ftp(data_connection_detail)

主程序

from load_file import get_connection
from load_file import download_files

def run_engine():
    while True:
        data = get_connection()
        download_files(data)



if __name__ == "__main__":
    run_engine()

请注意,我根本没有在第一个 function 中使用变量data_connection ,只是返回了它的数据。 在调用download_files时,我为变量使用了不同的名称。 这突出了一个上下文中的命名变量与它在另一个上下文中引用的 object 之间的区别。

暂无
暂无

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

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