我遇到了尝试声明全局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()
您没有将'global'放在'ftpConnect'中,所以它只是创建一个名为'ftp'的局部变量。 –