2016-03-07 109 views
0

我遇到了尝试声明全局ftp对象的问题。我想要在特定时间检查ftp连接并刷新或重新连接。我想使用一个全局变量,因为我想捕获另一个函数中的任何错误。Python错误:NameError:全局名称'ftp'未定义

我试过把'全球ftp'放在所有的地方,它似乎没有帮助任何地方。我有一种感觉,这与FTP(ftpIP)每次调用时返回一个ftp类的新实例有关,但我不确定。或者是不可能声明一个全局对象?

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

您没有将'global'放在'ftpConnect'中,所以它只是创建一个名为'ftp'的局部变量。 –

回答

1

的问题是,你在很多地方定义它,但需要你不初始化。尝试仅定义一次,并确保在尝试使用它之前对其进行初始化。

在同一个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() 
+0

然而,由于它解决了我的全局变量问题,因此将其标记为答案,我知道@mhawke提出了一个更合适的解决方案。 – user2836976

0
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 
1

其他人已经提供了答案,您的具体问题,保留使用全局变量。但你不应该以这种方式使用global。相反,请ftpConnect()返回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)) 
相关问题