I'm having an issue with trying to declare a global ftp object. I want the ftp connection to be check at certain times and refreshed or reconnected. 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. 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. 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:
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()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments