簡體   English   中英

Python錯誤:NameError:未定義全局名稱“ ftp”

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

我在嘗試聲明全局ftp對象時遇到問題。 我希望在某些時候檢查ftp連接並刷新或重新連接。 我試圖使用全局變量,因為我想捕獲另一個函數中的任何錯誤。

我嘗試將“ global 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()

問題是您在很多地方都定義了它,但是沒有根據需要對其進行初始化。 嘗試僅定義一次,並確保在嘗試使用它之前對其進行初始化。

下面的代碼導致相同的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()

其他人為您的特定問題提供了答案,這些答案保留了全局變量的使用。 但是您不必以這種方式使用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))
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