FTP和python问题

时间:2010-06-24 14:43:59

标签: python ftp ftplib

有人可以帮助我。

为什么它不起作用

import ftplib
import os

def readList(request):
         machine=[]
         login=[]
         password=[]
         for line in open("netrc"): #read netrc file
            old=line.strip()
            line=line.strip().split()
            if old.startswith("machine"): machine.append(line[-1])
            if old.startswith("login"): login.append(line[-1])
            if old.startswith("password"): password.append(line[-1])
            connectFtp(machine,login,password)

def connectFtp(machine,login,password):
  for i in range(len(machine)):
          try:
             ftp = ftplib.FTP(machine[i])
             print 'conected to ' + machine[i]
             ftp.login(login[i],password[i])
             print 'login - ' + login[i] + ' pasword -' + password[i]
           except Exception,e:
             print e
           else:
       ftp.cwd("PublicFolder")
    print 'PublicFolder'

def upload(filename, file):
       readList()
          ext = os.path.splitext(file)[1]
            if ext in (".txt", ".htm", ".html"):
            ftp.storlines("STOR " + filename, open(file))
            else:
             ftp.storbinary("STOR " + filename, open(file, "rb"), 1024)
             print 'success... yra'

upload('test4.txt', r'c:\example2\media\uploads\test4.txt')`

当它在一起时它正在工作。但是当我把它分开来发生功能时,我无法理解它是什么。

2 个答案:

答案 0 :(得分:0)

(除了可怕的缩进问题,这可能是由于拙劣的复制和粘贴,否则你会得到语法错误了!)...:

确定范围问题,首先:connectFtp生成一个本地变量ftp,以便在函数完成后变量就会消失。然后upload尝试使用变量,但当然它不再存在了。

return ftp末尾添加connectFtp yield connectFtp,而不是readList中对循环的简单调用,并使用for ftp in readList():循环在upload

答案 1 :(得分:0)

这样的东西?

import os


def readList(request):
    machine = []
    login = []
    password = []
    for line in open("netrc"):  # read netrc file
        old = line.strip()
        line = line.strip().split()
        if old.startswith("machine"): machine.append(line[-1])
        if old.startswith("login"): login.append(line[-1])
        if old.startswith("password"): password.append(line[-1])
        yield connectFtp


def connectFtp(machine, login, password):
    for i in range(len(machine)):


try:
    ftp = ftplib.FTP(machine[i])
    print 'conected to ' + machine[i]
    ftp.login(login[i], password[i])
    print 'login - ' + login[i] + ' pasword -' + password[i]
except Exception, e:
    print e
else:
    ftp.cwd("PublicFolder")
    print 'PublicFolder'
    return (ftp)


def upload(filename, file):
    for ftp in readList():
        ext = os.path.splitext(file)[1]
    if ext in (".txt", ".htm", ".html"):
        ftp.storlines("STOR " + filename, open(file))
    else:
    ftp.storbinary("STOR " + filename, open(file, "rb"), 1024)
    print 'success... yra'

upload('test4.txt', r'c:\example2\media\uploads\test4.txt')

第19行出错try: unindent不会计算任何外部缩进级别