我在尝试声明全局ftp对象时遇到问题。我希望在某些时候检查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()
答案 0 :(得分: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()
答案 1 :(得分: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))
答案 2 :(得分: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