cinap_lenrekadd hg and python4bb9e2215 years agoHistory
288 lines · 12.0 KB · TeX
RawDownload
\section{\module{ftplib} ---         FTP protocol client} \declaremodule{standard}{ftplib}\modulesynopsis{FTP protocol client (requires sockets).} \indexii{FTP}{protocol}\index{FTP!\module{ftplib} (standard module)} This module defines the class \class{FTP} and a few related items.The \class{FTP} class implements the client side of the FTPprotocol.  You can use this to write Pythonprograms that perform a variety of automated FTP jobs, such asmirroring other ftp servers.  It is also used by the module\refmodule{urllib} to handle URLs that use FTP.  For more informationon FTP (File Transfer Protocol), see Internet \rfc{959}. Here's a sample session using the \module{ftplib} module: \begin{verbatim}>>> from ftplib import FTP>>> ftp = FTP('ftp.cwi.nl')   # connect to host, default port>>> ftp.login()               # user anonymous, passwd anonymous@>>> ftp.retrlines('LIST')     # list directory contentstotal 24418drwxrwsr-x   5 ftp-usr  pdmaint     1536 Mar 20 09:48 .dr-xr-srwt 105 ftp-usr  pdmaint     1536 Mar 21 14:32 ..-rw-r--r--   1 ftp-usr  pdmaint     5305 Mar 20 09:48 INDEX . . .>>> ftp.retrbinary('RETR README', open('README', 'wb').write)'226 Transfer complete.'>>> ftp.quit()\end{verbatim} The module defines the following items: \begin{classdesc}{FTP}{\optional{host\optional{, user\optional{,                       passwd\optional{, acct}}}}}Return a new instance of the \class{FTP} class.  When\var{host} is given, the method call \code{connect(\var{host})} ismade.  When \var{user} is given, additionally the method call\code{login(\var{user}, \var{passwd}, \var{acct})} is made (where\var{passwd} and \var{acct} default to the empty string when not given).\end{classdesc} \begin{datadesc}{all_errors}The set of all exceptions (as a tuple) that methods of \class{FTP}instances may raise as a result of problems with the FTP connection(as opposed to programming errors made by the caller).  This setincludes the four exceptions listed below as well as\exception{socket.error} and \exception{IOError}.\end{datadesc} \begin{excdesc}{error_reply}Exception raised when an unexpected reply is received from the server.\end{excdesc} \begin{excdesc}{error_temp}Exception raised when an error code in the range 400--499 is received.\end{excdesc} \begin{excdesc}{error_perm}Exception raised when an error code in the range 500--599 is received.\end{excdesc} \begin{excdesc}{error_proto}Exception raised when a reply is received from the server that doesnot begin with a digit in the range 1--5.\end{excdesc}  \begin{seealso}  \seemodule{netrc}{Parser for the \file{.netrc} file format.  The file                    \file{.netrc} is typically used by FTP clients to                    load user authentication information before prompting                    the user.}  \seetext{The file \file{Tools/scripts/ftpmirror.py}\index{ftpmirror.py}           in the Python source distribution is a script that can mirror           FTP sites, or portions thereof, using the \module{ftplib} module.           It can be used as an extended example that applies this module.}\end{seealso}  \subsection{FTP Objects \label{ftp-objects}} Several methods are available in two flavors: one for handling textfiles and another for binary files.  These are named for the commandwhich is used followed by \samp{lines} for the text version or\samp{binary} for the binary version. \class{FTP} instances have the following methods: \begin{methoddesc}{set_debuglevel}{level}Set the instance's debugging level.  This controls the amount ofdebugging output printed.  The default, \code{0}, produces nodebugging output.  A value of \code{1} produces a moderate amount ofdebugging output, generally a single line per request.  A value of\code{2} or higher produces the maximum amount of debugging output,logging each line sent and received on the control connection.\end{methoddesc} \begin{methoddesc}{connect}{host\optional{, port}}Connect to the given host and port.  The default port number is \code{21}, asspecified by the FTP protocol specification.  It is rarely needed tospecify a different port number.  This function should be called onlyonce for each instance; it should not be called at all if a host wasgiven when the instance was created.  All other methods can only beused after a connection has been made.\end{methoddesc} \begin{methoddesc}{getwelcome}{}Return the welcome message sent by the server in reply to the initialconnection.  (This message sometimes contains disclaimers or helpinformation that may be relevant to the user.)\end{methoddesc} \begin{methoddesc}{login}{\optional{user\optional{, passwd\optional{, acct}}}}Log in as the given \var{user}.  The \var{passwd} and \var{acct}parameters are optional and default to the empty string.  If no\var{user} is specified, it defaults to \code{'anonymous'}.  If\var{user} is \code{'anonymous'}, the default \var{passwd} is\code{'anonymous@'}.  This function should be called onlyonce for each instance, after a connection has been established; itshould not be called at all if a host and user were given when theinstance was created.  Most FTP commands are only allowed after theclient has logged in.\end{methoddesc} \begin{methoddesc}{abort}{}Abort a file transfer that is in progress.  Using this does not alwayswork, but it's worth a try.\end{methoddesc} \begin{methoddesc}{sendcmd}{command}Send a simple command string to the server and return the responsestring.\end{methoddesc} \begin{methoddesc}{voidcmd}{command}Send a simple command string to the server and handle the response.Return nothing if a response code in the range 200--299 is received.Raise an exception otherwise.\end{methoddesc} \begin{methoddesc}{retrbinary}{command,    callback\optional{, maxblocksize\optional{, rest}}}Retrieve a file in binary transfer mode.  \var{command} should be anappropriate \samp{RETR} command: \code{'RETR \var{filename}'}.The \var{callback} function is called for each block of data received,with a single string argument giving the data block.The optional \var{maxblocksize} argument specifies the maximum chunk size toread on the low-level socket object created to do the actual transfer(which will also be the largest size of the data blocks passed to\var{callback}).  A reasonable default is chosen. \var{rest} means thesame thing as in the \method{transfercmd()} method.\end{methoddesc} \begin{methoddesc}{retrlines}{command\optional{, callback}}Retrieve a file or directory listing in \ASCII{} transfer mode.\var{command} should be an appropriate \samp{RETR} command (see\method{retrbinary()}) or a \samp{LIST} command (usually just the string\code{'LIST'}).  The \var{callback} function is called for each line,with the trailing CRLF stripped.  The default \var{callback} printsthe line to \code{sys.stdout}.\end{methoddesc} \begin{methoddesc}{set_pasv}{boolean}Enable ``passive'' mode if \var{boolean} is true, other disablepassive mode.  (In Python 2.0 and before, passive mode was off bydefault; in Python 2.1 and later, it is on by default.)\end{methoddesc} \begin{methoddesc}{storbinary}{command, file\optional{, blocksize}}Store a file in binary transfer mode.  \var{command} should be anappropriate \samp{STOR} command: \code{"STOR \var{filename}"}.\var{file} is an open file object which is read until \EOF{} using its\method{read()} method in blocks of size \var{blocksize} to provide thedata to be stored.  The \var{blocksize} argument defaults to 8192.\versionchanged[default for \var{blocksize} added]{2.1}\end{methoddesc} \begin{methoddesc}{storlines}{command, file}Store a file in \ASCII{} transfer mode.  \var{command} should be anappropriate \samp{STOR} command (see \method{storbinary()}).  Lines areread until \EOF{} from the open file object \var{file} using its\method{readline()} method to provide the data to be stored.\end{methoddesc} \begin{methoddesc}{transfercmd}{cmd\optional{, rest}}Initiate a transfer over the data connection.  If the transfer isactive, send a \samp{EPRT} or  \samp{PORT} command and the transfer command specifiedby \var{cmd}, and accept the connection.  If the server is passive,send a \samp{EPSV} or \samp{PASV} command, connect to it, and start the transfercommand.  Either way, return the socket for the connection. If optional \var{rest} is given, a \samp{REST} command issent to the server, passing \var{rest} as an argument.  \var{rest} isusually a byte offset into the requested file, telling the server torestart sending the file's bytes at the requested offset, skippingover the initial bytes.  Note however that RFC959 requires only that \var{rest} be a string containing charactersin the printable range from ASCII code 33 to ASCII code 126.  The\method{transfercmd()} method, therefore, converts\var{rest} to a string, but no check isperformed on the string's contents.  If the server doesnot recognize the \samp{REST} command, an\exception{error_reply} exception will be raised.  If this happens,simply call \method{transfercmd()} without a \var{rest} argument.\end{methoddesc} \begin{methoddesc}{ntransfercmd}{cmd\optional{, rest}}Like \method{transfercmd()}, but returns a tuple of the dataconnection and the expected size of the data.  If the expected sizecould not be computed, \code{None} will be returned as the expectedsize.  \var{cmd} and \var{rest} means the same thing as in\method{transfercmd()}.\end{methoddesc} \begin{methoddesc}{nlst}{argument\optional{, \ldots}}Return a list of files as returned by the \samp{NLST} command.  Theoptional \var{argument} is a directory to list (default is the currentserver directory).  Multiple arguments can be used to passnon-standard options to the \samp{NLST} command.\end{methoddesc} \begin{methoddesc}{dir}{argument\optional{, \ldots}}Produce a directory listing as returned by the \samp{LIST} command,printing it to standard output.  The optional \var{argument} is adirectory to list (default is the current server directory).  Multiplearguments can be used to pass non-standard options to the \samp{LIST}command.  If the last argument is a function, it is used as a\var{callback} function as for \method{retrlines()}; the defaultprints to \code{sys.stdout}.  This method returns \code{None}.\end{methoddesc} \begin{methoddesc}{rename}{fromname, toname}Rename file \var{fromname} on the server to \var{toname}.\end{methoddesc} \begin{methoddesc}{delete}{filename}Remove the file named \var{filename} from the server.  If successful,returns the text of the response, otherwise raises\exception{error_perm} on permission errors or\exception{error_reply} on other errors.\end{methoddesc} \begin{methoddesc}{cwd}{pathname}Set the current directory on the server.\end{methoddesc} \begin{methoddesc}{mkd}{pathname}Create a new directory on the server.\end{methoddesc} \begin{methoddesc}{pwd}{}Return the pathname of the current directory on the server.\end{methoddesc} \begin{methoddesc}{rmd}{dirname}Remove the directory named \var{dirname} on the server.\end{methoddesc} \begin{methoddesc}{size}{filename}Request the size of the file named \var{filename} on the server.  Onsuccess, the size of the file is returned as an integer, otherwise\code{None} is returned.  Note that the \samp{SIZE} command is not standardized, but is supported by many common server implementations.\end{methoddesc} \begin{methoddesc}{quit}{}Send a \samp{QUIT} command to the server and close the connection.This is the ``polite'' way to close a connection, but it may raise anexception of the server reponds with an error to the\samp{QUIT} command.  This implies a call to the \method{close()}method which renders the \class{FTP} instance useless for subsequentcalls (see below).\end{methoddesc} \begin{methoddesc}{close}{}Close the connection unilaterally.  This should not be applied to analready closed connection such as after a successful call to\method{quit()}.  After this call the \class{FTP} instance should notbe used any more (after a call to \method{close()} or\method{quit()} you cannot reopen the connection by issuing another\method{login()} method).\end{methoddesc}