当前位置: 首页>>代码示例>>Python>>正文


Python FTP_TLS.cwd方法代码示例

本文整理汇总了Python中ftplib.FTP_TLS.cwd方法的典型用法代码示例。如果您正苦于以下问题:Python FTP_TLS.cwd方法的具体用法?Python FTP_TLS.cwd怎么用?Python FTP_TLS.cwd使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ftplib.FTP_TLS的用法示例。


在下文中一共展示了FTP_TLS.cwd方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: sendUpdateFilesFtp

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
def sendUpdateFilesFtp():
    print "---- Send update files by FTP"
    global serverFtp
    global userFtp
    global passFtp
    
    from ftplib import FTP_TLS
    ftps = FTP_TLS(serverFtp)
    ftps.set_debuglevel(1)
    ftps.login(userFtp, passFtp)
    ftps.prot_p()
    ftps.cwd('/files/updates')
    
    ftps.storbinary('STOR ' + 'file_list.md5', open(quiterssFileRepoPath + '\\file_list.md5', 'rb'))
    ftps.storbinary('STOR ' + 'VersionNo.h', open(quiterssSourcePath + '\\src\\VersionNo.h', 'rb'))
    ftps.storbinary('STOR ' + 'HISTORY_EN', open(quiterssSourcePath + '\\HISTORY_EN', 'rb'))
    ftps.storbinary('STOR ' + 'HISTORY_RU', open(quiterssSourcePath + '\\HISTORY_RU', 'rb'))
    
    prepareFileList7z = []
    for file in prepareFileList:
        prepareFileList7z.append(file + '.7z')

    for fileName in prepareFileList7z:
        ftps.storbinary('STOR ' + 'windows' + fileName.replace('\\','/'), open(quiterssFileRepoPath + '\\windows' + fileName, 'rb'))

    ftps.quit()
开发者ID:barkinet,项目名称:quite-rss.tools,代码行数:28,代码来源:prepare-install.py

示例2: sendPackagesFtp

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
def sendPackagesFtp():
    print "---- Send packages by FTP"
    global serverFtp
    global userFtp
    global passFtp

    from ftplib import FTP_TLS
    ftps = FTP_TLS(serverFtp)
    ftps.set_debuglevel(1)
    ftps.login(userFtp, passFtp)
    ftps.prot_p()
    try:
        ftps.sendcmd('MKD ' + '/files/' + strProductVer)
    except Exception:
        print 'Directory already exists'
    ftps.cwd('/files/' + strProductVer)
    
    filesListFtp = ftps.nlst()
    filesList = os.listdir(packagesPath)
    newFilesList = [e for e in filesList if not(e in filesListFtp)]
    
    for fileName in newFilesList:
        ftps.storbinary('STOR ' + fileName, open(packagesPath + '\\' + fileName, 'rb'))

    ftps.quit()
开发者ID:barkinet,项目名称:quite-rss.tools,代码行数:27,代码来源:prepare-install.py

示例3: sync

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
 def sync(self):
     """
     downloads all needed_files from self.hostname (FTP)
     of the downloaded files, extracts .gz files to same local_working_dir
         -using self.extract function
     parses the .txt downloaded needed_files
         -using the self.parse function
     """
     ftps = FTP_TLS(self.hostname) # connect to host, default port
     ftps.login(self.username, self.password)
     ftps.prot_p()
     ftps.cwd(self.remote_dir) # change into "logs" directory
     ftps.retrlines('LIST *.gz *.txt', self.ftp_list_callback) # list directory contents
     for needed_file in self.needed_files:
         if self.logging:
             print "Writing {0} to {1}...".format(needed_file, self.local_working_dir)
         ftps.retrbinary("RETR " + needed_file, open(os.path.join(self.local_working_dir, needed_file), 'wb').write)
     if self.logging:
         print "done syncing files"
     for needed_file in self.needed_files:
         if needed_file.endswith(".gz"):
             self.extract(os.path.join(self.local_working_dir, needed_file))
         txt_file_name = needed_file.replace('.gz','')#if already a .txt file, this is unnceccessary but works.
         self.parse(txt_file_name)
     if self.logging:
         print "done extracting/parsing .gz files"
     ftps.quit()
开发者ID:tropo,项目名称:ftp_cdr_tool,代码行数:29,代码来源:ftp_cdr_tool.py

示例4: connect

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
 def connect(self):
     #初始化 FTP 链接
     if self.ftp_ssl:
         ftp = FTPS()
     else:
         ftp = FTP()
     print('-'*20+self.ftp_name+'-'*20)
     print('connect '+('ftps' if self.ftp_ssl else 'ftp')+'://'+self.ftp_host+':'+self.ftp_port)
     try:
         ftp.connect(self.ftp_host,self.ftp_port)
     except Exception as e:
         print (e)
         print ('connect ftp server failed')
         sys.exit()
     try:
         ftp.login(self.ftp_user,self.ftp_passwd)
         print ('login ok')
     except Exception as e:#可能服务器不支持ssl,或者用户名密码不正确
         print (e)
         print ('Username or password are not correct')
         sys.exit()        
     
     if self.ftp_ssl:
         try:    
             ftp.prot_p()
         except Exception as e:
             print (e)
             print ('Make sure the SSL is on ;')
         
     print(ftp.getwelcome())
     ftp.cwd(self.ftp_webroot)
     print('current path: '+ftp.pwd())
     
     self.ftp=ftp
开发者ID:ttym7993,项目名称:sync_web,代码行数:36,代码来源:sync_web.py

示例5: connexionftp

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
def connexionftp(adresseftp, nom, mdpasse, passif):
	"""connexion au serveur ftp et ouverture de la session
	   - adresseftp: adresse du serveur ftp
	   - nom: nom de l'utilisateur enregistré ('anonymous' par défaut)
	   - mdpasse: mot de passe de l'utilisateur ('[email protected]' par défaut)
	   - passif: active ou désactive le mode passif (True par défaut)
	   retourne la variable 'ftplib.FTP' après connexion et ouverture de session
	"""
	try:
		verbose('Attente connexion FTP .....')
		if modeSSL:
			ftp = FTP_TLS()
			ftp.connect(adresseftp, 21)
			ftp.login(nom, mdpasse)
			ftp.prot_p()
			ftp.set_pasv(passif)
		else:
			ftp = (ftplib.FTP(adresseftp, nom, mdpasse))
			
		ftp.cwd(destination)
		verbose ('Destination : '+destination)
		verbose('Connexion FTP OK')
		etat = ftp.getwelcome()
		verbose("Etat : "+ etat) 
		return ftp
	except:
		verbose('Connexion FTP impossible', True)
		suppressionDossierTemp(dossierTemporaireFTP)
		sys.exit()
开发者ID:Michelgard,项目名称:backup_serveur,代码行数:31,代码来源:backupserveurFTP.py

示例6: main

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
def main():
	global ftp_client

	scan_arguments()
	ftp_client = FTP(host)

	try:
		ftp_client.login(username, password)
	except ftplib.all_errors as e:
		print "ERROR: cannot login with username '{0}' and relative password.\nMessage returned from server:".format(username)
		print e
		return

	try:
		ftp_client.cwd(remote_dir)
	except ftplib.all_errors as e:
		print "ERROR: emote directory '{0}' not existing.\nMessage returned from server:".format(remote_dir)
		print e
		return
	else:
		files = ftp_client.nlst()
		print_directory_content(files)
		setup_folder()
		download_files(remote_dir, files)
		if compress:
			create_zip(local_dir)

	try:
		ftp_client.close()
		print "!!!!! OPERATION COMPLETED SUCCESSFULLY !!!!!"
	except ftplib.all_errors as e:
		print "ERROR: cannot close the connection properly.\nMessage from server:"
		print e
开发者ID:Diiaablo95,项目名称:mirr_downloader,代码行数:35,代码来源:mirr_downloader.py

示例7: getfiles

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
def getfiles(server, port, user, password, db):
	sqliteconnection = sqlite3.connect(db)
	sqlitecursor = sqliteconnection.cursor()

	sqlitecursor.execute('''CREATE TABLE IF NOT EXISTS latest (date int, CONSTRAINT 'id_UNIQUE' UNIQUE ('date'))''')
	sqliteconnection.commit()

	sqlitecursor.execute('''SELECT date FROM files WHERE date = (SELECT MAX(date) FROM files) LIMIT 1''')
	latestfile = sqlitecursor.fetchone()

	sqlitecursor.execute('''SELECT date FROM latest WHERE date = (SELECT MAX(date) FROM latest) LIMIT 1''')
	latestfetch = sqlitecursor.fetchone()

	if latestfetch is None:
		latestfetch = 0

	if latestfetch < latestfile:
		ftpsconnection = FTP_TLS()
		ftpsconnection.connect(server, port)
		ftpsconnection.auth()
		ftpsconnection.prot_p()
		ftpsconnection.login(user, password)
		ftpsconnection.prot_p()

		sqlitecursor.execute('''SELECT name FROM files WHERE date > %d''' % latestfetch)
		filestofetch = sqlitecursor.fetchall()

		for currfile in filestofetch:
        		ftpsconnection.cwd(currfile[0])
			filenames = ftpsconnection.nlst()

			for filename in filenames:
				print 'Now saving /mnt/folder' + currfile[0] + '/' + filename
				localfile = open('/mnt/folder' + currfile + '/' + filename, 'wb')
				ftpsconnection.retrbinary('RETR ' + filename, localfile.write)
				localfile.close()


	sqliteconnection.execute('''INSERT OR IGNORE INTO latest VALUES (%d)''' % time.time())
	sqliteconnection.commit()

	sqliteconnection.close()
	ftpsconnection.quit()
	ftpsconnection.close()
开发者ID:sikevux,项目名称:FTPSync,代码行数:46,代码来源:Sync.py

示例8: connect

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
def connect(velkost_ftp,port):
    ftp=FTP_TLS(server,meno2,ps,port)   
    ftp.prot_p()
    ftp.cwd(my_list[2]) 
    print "Posielam subor. Cakajte prosim."
    obsah=open(file_to_send, 'rb')
    obsah.close()
    ftp.storbinary('STOR %s' % file_to_send, open(file_to_send, 'rb'))
    obsah.close()
    print "Subor odoslany [OK]"
    print "Obsah adresara na serveri:"
    ftp.retrlines("LIST")
    size_ftp=ftp.nlst()
    pocet=len(size_ftp)
    velkost_ftp_subor=size_ftp[pocet-1] #berie posledne pridany subor zo zoznamu
    ftp.sendcmd("TYPE i")
    velkost_ftp=ftp.size(velkost_ftp_subor) 
    ftp.close()
    return velkost_ftp
开发者ID:peterjs,项目名称:pyPNC,代码行数:21,代码来源:pypnc.py

示例9: download

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
def download(downloaded, user, passwd, all_files=False, filename=None):
    # Connect to the MAPS ftp server over FTPS
    ftps = FTP_TLS('ftps.tsi.telecom-paristech.fr')
    print 'Connected to MAPS FTP over TLS.'
    try:
        ftps.login(user=user, passwd=passwd)
        ftps.cwd('maps')
    except error_perm:
        print "Incorrect username/password" ; quit

    ftps.retrlines('LIST *.zip', get_file_list)

    if filename is not None:
        if not in_downloads(files, filename): print 'File not found' ; return
        print 'Downloading', filename
        res = ftps.retrbinary('RETR '+filename, open('./downloads/'+filename, 'wb').write)
        ftps.close()
        return [(filename, 0)]
    
    if len(files) == len(downloaded):
        print "All MAPS files downloaded. Continuing."
        return
    
    if all_files:
        for f, s in files:
            if not in_downloads(downloaded, f):
                print "Downloading", f, "of size", s, "bytes"
                res = ftps.retrbinary('RETR '+f, open('./downloads/'+f, 'wb').write)
    elif filename is None:
        f, s = random.choice(files)
        while in_downloads(downloaded, f):
            f, s = random.choice(files)
        
        print "Downloading", f, "of size", s, "bytes"
        res = ftps.retrbinary('RETR '+f, open('./downloads/'+f, 'wb').write)

    ftps.close()

    if all_files: return files
    return [(f, s)]
开发者ID:jbarrow,项目名称:capstone,代码行数:42,代码来源:maps_download.py

示例10: __init__

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
class FTPES:
    def __init__(self, host, port=None, username=None, password=None, remote_path=None, absolute_zipfile_path=None):
        """
        This is a helper class to manage the FTP commands from the ftplib.

        @param host: The host for the connection.
        @type host: String
        @param port: The post for the connection.
        @type port: Integer
        @param username: The username for the connection. Leave blank to use "anonymous".
        @type username: String
        @param password: The password for the connection. Leave empty for none.
        @type password: String
        @param remote_path: The remote path of the server in which the zip file should be uploaded. If the path does not
                            exists, it will be created (recursive).
        @type remote_path: String
        @param absolute_zipfile_path: The absolute LOCAL filepath of the zip file.
        @type absolute_zipfile_path: String
        """
        self.ftps = None
        self._host = host
        self._port = port
        self._username = username
        self._password = password
        self._remote_path = remote_path
        self._absolute_zipfile_path = absolute_zipfile_path
        self._bytesWritten = 0;
        self._totalFileSize = os.path.getsize(self._absolute_zipfile_path)
        self._uploadCallback = None
        self._currentProgress = 0

        # make the remote path relative if it isnt absolute or relative yet
        if self._remote_path is not None and self._remote_path.startswith(
                '.') is False and self._remote_path.startswith('/') is False:
            self._remote_path = './' + self._remote_path

        if self._username is None:
            self._username = 'anonymous'

        if self._port is None:
            self._port = 22

    def connect(self):
        """
        Try to connect to the FTP server.
        Raise an error if something went wrong.
        """
        try:
            self.ftps = FTP_TLS()
            self.ftps.set_pasv(True)
            self.ftps.connect(self._host, self._port)
        except socket.gaierror:
            raise

    def login(self):
        """
        Try to login in on the FTP server.
        Raise an error if something went wrong.
        """
        try:
            self.ftps.login(self._username, self._password)
            self.ftps.prot_p()
        except ftplib.error_perm:
            raise

    def cwd(self):
        """
        Try to switch the working directory on the FTP server (if set in the settings).
        If the path does not exist, it will be created.
        """
        if self._remote_path is not None:
            try:
                self.ftps.cwd(self._remote_path)
            except ftplib.error_perm:
                self.create_directory_tree(self._remote_path)
            except IOError:
                raise

    def create_directory_tree(self, current_directory):
        """
        Helper function to create the remote path.

        @param current_directory: The current working directory.
        @type current_directory: String
        """
        if current_directory is not "":
            try:
                self.ftps.cwd(current_directory)
            except ftplib.error_perm:
                self.create_directory_tree("/".join(current_directory.split("/")[:-1]))
                self.ftps.mkd(current_directory)
                self.ftps.cwd(current_directory)
            except IOError:
                raise

    def upload(self, callback=None):
        """
        The upload function.

        @param callback: The callback function for the upload progress.
#.........这里部分代码省略.........
开发者ID:pixel-shock,项目名称:dropzone-ftpes-upload,代码行数:103,代码来源:ftpes.py

示例11: FTPClient

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]

#.........这里部分代码省略.........
            self._mh.demsg(
                'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere())
            return None

    def change_dir(self, path):
        """Method changes remote working directory

        Args:
           path (str): new remote path

        Returns:
           bool: result         

        Raises:
           event: ftp_before_change_dir        

        """

        try:

            self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
                'htk_ftp_change_dir', path), self._mh.fromhere())

            if (not self._is_connected):
                self._mh.demsg('htk_on_warning', self._mh._trn.msg(
                    'htk_ftp_not_connected'), self._mh.fromhere())
                return False

            ev = event.Event('ftp_before_change_dir', path)
            if (self._mh.fire_event(ev) > 0):
                path = ev.argv(0)

            if (ev.will_run_default()):
                self._client.cwd(path)
                self._path = self._client.pwd()

            self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
                'htk_ftp_cur_dir', self._path), self._mh.fromhere())
            return True

        except all_errors as ex:
            self._mh.demsg(
                'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere())
            return False

    def download_file(self, remote_path, local_path=None):
        """Method downloads file from server

        Args:
           remote_path (str): remote path
           local_path (str): local path, default ./filename

        Returns:
           bool: result         

        Raises:
           event: ftp_before_download_file
           event: ftp_after_download_file    

        """

        try:

            self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
                'htk_ftp_downloading_file', remote_path), self._mh.fromhere())
开发者ID:hydratk,项目名称:hydratk-lib-network,代码行数:69,代码来源:ftp_client.py

示例12: print

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
    #See http://stackoverflow.com/questions/10207628/python-module-ftplib-ftp-tls-error-530
    #Try TLS Lite or M2Crypto both are FTP/TLS client and server.

    #ftps.login(user,secret)

    ftps.sendcmd('USER ' + user)
    ftps.sendcmd('PASS ' + secret)
    print(ftps.getwelcome())
    print('CURRENT WORKING DIRECTORY IS:',ftps.pwd())
    #Enable data encryption
    # TODO solve the encryption problem
    #ftps.prot_p()
    #define default DIR
    d = 'feeds'
    #Change to default DIR
    ftps.cwd(d)
    #Build list of files on servers
    l = ftps.nlst()
    l.sort()
    for i in l:
        print(i)
    #Assign last element to var
    litem = len(l)-1
    print("MOST RECENT FILE ON SERVER IS; ",l[litem])

    g = l[litem]
    #Define local file
    t = d + '/' + g
    if os.path.exists(t):
        print("FILE" ,g," EXISTS,WILL NOT DOWNLOAD FROM HOST:",host)
    else:
开发者ID:yaowenqiang,项目名称:python,代码行数:33,代码来源:ftp.py

示例13: group_listing

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
data['bot_id'] = BOT_ID

def group_listing():
    # Get list of groups user is a member of
    r = requests.get('%s/groups?token=%s' % (GROUPME_API_URL, TOKEN))
    resp = r.json()

    print 'Groups:'
    for item in resp['response']:
        print item['name']

# Securely connect to FTP server
ftps = FTP_TLS(HOST, USER, PASSWD)
ftps.prot_p()
# Change working directory to directory containing images
ftps.cwd(IMAGE_DIRECTORY)
# Get list of items in current directory
directory_list = ftps.nlst()
# Get list of images
image_list = [item for item in directory_list if '.jpg' in item]
# Save oldest & newest images
images_to_upload = []
if image_list:
    # Add first image
    images_to_upload.append(image_list[0])
    if len(image_list) > 1:
        # Add last image (if more than 1 image)
        images_to_upload.append(image_list[len(image_list)-1])
    # Download oldest & newest image
    for image in images_to_upload:
        print 'Downloading %s...' % image
开发者ID:MarkVLK,项目名称:GroupMe-Notifier,代码行数:33,代码来源:GroupMeNotify.py

示例14: FTPSession

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
class FTPSession(object):
    """ Attempt to create some robustness and performance to FTPing """

    def __init__(self, server, username, password, tmpdir="/tmp", timeout=60):
        """Build a FTP session """
        self.conn = None
        self.server = server
        self.username = username
        self.password = password
        self.tmpdir = tmpdir
        self.timeout = timeout

    def _connect(self):
        """Connect to FTP server """
        if self.conn is not None:
            return
        logging.debug("Creating new connection to server %s", self.server)
        not_connected = True
        attempt = 1
        while not_connected and attempt < 6:
            try:
                self.conn = FTP_TLS(self.server, timeout=self.timeout)
                self.conn.login(self.username, self.password)
                self.conn.prot_p()
                not_connected = False
            except Exception as exp:
                logging.debug(exp)
                time.sleep(5)
                self.close()
            attempt += 1
        if not_connected is True:
            raise Exception("Failed to make FTP connection after 5 tries!")

    def _reconnect(self):
        """ First attempt to shut down connection and then reconnect """
        logging.debug("_reconnect() was called...")
        try:
            self.conn.quit()
            self.conn.close()
        except:
            pass
        finally:
            self.conn = None
        self._connect()

    def _put(self, path, localfn, remotefn):
        """ """
        self.chdir(path)
        sz = os.path.getsize(localfn)
        if sz > 14000000000:
            # Step 1 Split this big file into 14GB chunks, each file will have
            # suffix .aa then .ab then .ac etc
            basefn = os.path.basename(localfn)
            cmd = "split --bytes=14000M %s %s/%s." % (localfn, self.tmpdir, basefn)
            subprocess.call(cmd, shell=True, stderr=subprocess.PIPE)
            files = glob.glob("%s/%s.??" % (self.tmpdir, basefn))
            for filename in files:
                suffix = filename.split(".")[-1]
                self.conn.storbinary("STOR %s.%s" % (remotefn, suffix), open(filename))
                os.unlink(filename)
        else:
            logging.debug("_put '%s' to '%s'", localfn, remotefn)
            self.conn.storbinary("STOR %s" % (remotefn,), open(localfn))
        return True

    def close(self):
        """ Good bye """
        try:
            self.conn.quit()
            self.conn.close()
        except:
            pass
        finally:
            self.conn = None

    def chdir(self, path):
        if self.pwd() == path.rstrip("/"):
            return
        self.conn.cwd("/")
        for dirname in path.split("/"):
            if dirname == "":
                continue
            bah = []
            self.conn.retrlines("NLST", bah.append)
            if dirname not in bah:
                logging.debug("Creating directory '%s'", dirname)
                self.conn.mkd(dirname)
            logging.debug("Changing to directory '%s'", dirname)
            self.conn.cwd(dirname)

    def pwd(self):
        """ Low friction function to get connectivity """
        self._connect()
        pwd = exponential_backoff(self.conn.pwd)
        if pwd is None:
            self._reconnect()
            pwd = exponential_backoff(self.conn.pwd)
        logging.debug("pwd() is currently '%s'", pwd)
        return pwd

#.........这里部分代码省略.........
开发者ID:akrherz,项目名称:pyIEM,代码行数:103,代码来源:ftpsession.py

示例15: ServerWatcher

# 需要导入模块: from ftplib import FTP_TLS [as 别名]
# 或者: from ftplib.FTP_TLS import cwd [as 别名]
class ServerWatcher(Watcher):

    downloadProgress = Signal((int, int,))
    uploadProgress = Signal((int, int,))
    # Si added:
    textStatus = Signal((str,))
    
    fileEvent = Signal((str,))
    fileEventCompleted = Signal()    
    loginCompleted = Signal((bool, str,))
    badFilenameFound = Signal((str,))

    LOCATION = 'server'
    TEST_FILE = 'iqbox.test'
    
    def __init__(self, host, ssl, parent=None):
        """
        Initializes parent class and attributes. Decides
        whether to use `FTP_TLS` or `FTP` based on the `ssl` param.
        
        :param host: Location of the FTP server
        :param ssl: Tells whether the FTP needs to support TLS or not
        :param parent: Reference to a `QObject` instance a parent
        """
        
        super(ServerWatcher, self).__init__(parent)
        
        self.interval = 5000
        self.localdir = ''
        self.deleteQueue = []
        self.downloadQueue = []
        self.uploadQueue = []
        self.warnedNames = []
        self.ftp = None 
        self.useSSL = ssl
        self.host = host
        self.preemptiveCheck = False
        self.preemptiveActions = []
        self.testFile = 'iqbox.test'
        
    @property
    def currentdir(self):
        """Returns the current working directory at the server"""
        
        return self.ftp.pwd()
        
    def setLocalDir(self, localdir):
        """
        Sets the local directory used to stored all
        downloaded files. Creates the directory if needed.
        
        :param localdir: Absolute path to local directory
        """
        
        self.localdir = localdir
        if not os.path.exists(self.localdir):
            os.makedirs(self.localdir)
    
    @pause_timer
    @Slot()
    def checkout(self):
        """
        Recursively checks out all files on the server.
        Returns a dictionary of files on the server with their last modified date.
        
        :param download: Indicates whether or not the files should be downloaded
        """
        
        # Check  `self.deleteQueue`, `self.uploadQueue` and `self.downloadQueue` queues.
        # These tasks are done in queues to make sure all FTP commands
        # are done sequentially, in the same thread.
        self.deleteAll()
        self.uploadAll()
        self.downloadAll()
        
        # Handy list to keep track of the checkout process.
        # This list contain absolute paths only.
        checked_dirs = list()

        # Sets '/' as initial directory and initializes `downloading_dir`
        self.ftp.cwd('/')
        downloading_dir = self.currentdir
        check_date = dt.utcnow()

        sidirlist = list()

        root_cached = False
        
        fileC = 0
        while True:
            # Gets the list of sub directories and files inside the 
            # current directory `downloading_dir`.
            self.textStatus.emit('Remote scan- Downloading folder list of '+downloading_dir+'...')
            
            if root_cached and downloading_dir == '/':
                dir_subdirs = saved_root_dirs
                dirfiles = saved_root_files
            else:
                
                dir_subdirs = self.getDirs(downloading_dir)
#.........这里部分代码省略.........
开发者ID:ShareByLink,项目名称:iqbox-ftp,代码行数:103,代码来源:watchers.py


注:本文中的ftplib.FTP_TLS.cwd方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。