Python Error: NameError: global name 'ftp' is not defined

Python Error: NameError: global name 'ftp' is not defined

我在尝试声明全局 ftp 对象时遇到问题。我希望在特定时间检查 ftp 连接并刷新或重新连接。我正在尝试使用全局变量,因为我想捕获另一个函数中的任何错误。

我试过把 'global ftp' 放在各处,但似乎无济于事。我觉得这与 FTP(ftpIP) returns 每次调用 ftp class 的新实例有关,但我不确定.还是不能声明全局对象?

def ftpKeepAlive():
    global ftp
    # Keep FTP alive
    ftp.voidcmd('NOOP')         # Send a 'NOOP' command every 30 seconds

def ftpConnect():
    try:
        ftp = FTP(ftpIP)                # This times out after 20 sec
        ftp.login(XXXXX)
        ftp.cwd(ftpDirectory)

        ftp_status = 1

    except Exception, e:
        print str(e)
        ftp_status = 0
        pass



# Initialize FTP
ftpIP = '8.8.8.8'           # ftp will fail on this IP
ftp_status = 0

global ftp
ftpConnect()


while (1):
    if (second == 30):
        global ftp
        ftpKeepAlive()
def ftpConnect():
    global ftp, ftpIP, ftp_status       # add this...
    try:
        ftp = FTP(ftpIP)                # This times out after 20 sec
        ftp.login(XXXXX)
        ftp.cwd(ftpDirectory)

        ftp_status = 1

    except Exception, e:
        print str(e)
        ftp_status = 0
        pass

问题是你在那么多地方定义了它,却没有按需要初始化它。尝试只定义一次并确保在尝试使用它之前对其进行初始化。

下面的代码导致相同的 NameError:

global ftp
ftp.voidcmd('NOOP')

但是下面的代码会导致连接错误(正如预期的那样):

from ftplib import *

global ftp
ftp = FTP('127.0.0.1')
ftp.voidcmd('NOOP')

我对您的代码进行了一些调整,使其更接近我的意思。这是:

from ftplib import *

global ftp

def ftpKeepAlive():
    # Keep FTP alive
    ftp.voidcmd('NOOP')         # Send a 'NOOP' command every 30 seconds

def ftpConnect():
    try:
        ftp = FTP(ftpIP)                # This times out after 20 sec
        ftp.login(XXXXX)
        ftp.cwd(ftpDirectory)

        ftp_status = 1

    except Exception, e:
        print str(e)
        ftp_status = 0
        pass

# Initialize FTP
ftpIP = '8.8.8.8'           # ftp will fail on this IP
ftp_status = 0

ftpConnect()

while (1):
    if (second == 30):
        ftpKeepAlive()

其他人已经为您的特定问题提供了答案,这些问题保留了对全局变量的使用。但是您不需要以这种方式使用 global 。相反,让 ftpConnect() return FTP 客户端。然后您可以根据需要将该对象传递给其他函数。例如:

import time
from ftplib import FTP

def ftpKeepAlive(ftp):
    # Keep FTP alive
    ftp.voidcmd('NOOP')         # Send a 'NOOP' command

def ftpConnect(ftpIP, ftp_directory='.', user='', passwd=''):
    try:
        ftp = FTP(ftpIP)
        ftp.login(user, passwd)
        ftp.cwd(ftp_directory)
        return ftp
    except Exception, e:
        print str(e)

# Initialize FTP
ftpIP = '8.8.8.8'           # ftp will fail on this IP
ftp = ftpConnect(ftpIP)
if ftp:
    while (1):
        if (second == 30):
            ftpKeepAlive(ftp)
else:
    print('Failed to connect to FTP server at {}'.format(ftpIP))