简体   繁体   English

Python错误:NameError:未定义全局名称“ ftp”

[英]Python Error: NameError: global name 'ftp' is not defined

I'm having an issue with trying to declare a global ftp object. 我在尝试声明全局ftp对象时遇到问题。 I want the ftp connection to be check at certain times and refreshed or reconnected. 我希望在某些时候检查ftp连接并刷新或重新连接。 I'm trying to use a global variable, since I want to catch any errors within another function. 我试图使用全局变量,因为我想捕获另一个函数中的任何错误。

I've tried putting 'global ftp' all over the place, and it doesn't seem to help anywhere. 我尝试将“ global ftp”放在所有位置,但似乎无济于事。 I have a feeling that this has something to do with the fact that FTP(ftpIP) returns a new instance of the ftp class each time it's called, but I'm not sure. 我感觉这与以下事实有关FTP(ftpIP)返回ftp类的新实例,但是我不确定。 Or is it not possible to declare a global object? 还是无法声明全局对象?

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()

The problem is that you define it in that many places, but you don't initialize it as needed. 问题是您在很多地方都定义了它,但是没有根据需要对其进行初始化。 Try to define it only once and make sure you initialize it before trying to use it. 尝试仅定义一次,并确保在尝试使用它之前对其进行初始化。

The code below results in the same NameError: 下面的代码导致相同的NameError:

global ftp
ftp.voidcmd('NOOP')

But the code below results in a connection error (as expected): 但是下面的代码导致连接错误(按预期):

from ftplib import *

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

I've made some adjustments to your code to get it closer to what I mean. 我对您的代码进行了一些调整,以使其更接近我的意思。 Here it is: 这里是:

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()

Others have provided answers to your specific question that retain use of a global variable. 其他人为您的特定问题提供了答案,这些答案保留了全局变量的使用。 But you shouldn't need to use global in this manner. 但是您不必以这种方式使用global Instead, have ftpConnect() return the FTP client. 而是让ftpConnect()返回FTP客户端。 Then you can pass that object to other functions as required. 然后,您可以根据需要将该对象传递给其他函数。 For example: 例如:

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))
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

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

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