pythonic的最大公约数代码(一句话)
让人晕的一条函数式编程的代码

FTP下载程序(包括ascii和binary)

dcy posted @ 2009年8月23日 23:57 in Python with tags python 小玩意 , 4574 阅读

一条python写的程序,可以在ftp上下载东西,包括ascii模式和binary模式。

先讲讲ascii和binary:

 一般来说:
如果你用错误的模式传输你的图片,你将会无法看到图片,看到的会是乱码。
如果你用错误模式上传CGI脚本,那么就将无法运行你的脚本,会看到类似Server  500  Error的出错信息。
所以你必须使用正确的模式,图片和执行文件必须用BINARY模式,CGI脚本和普通HTML文件用ASCII模式上传.

ASCII和BINARY模式区别:

用HTML  和文本编写的文件必须用ASCII模式上传,用BINARY模式上传会破坏文件,导致文件执行出错。

BINARY模式用来传送可执行文件,压缩文件,和图片文件。
如果你用ASCII模式传,会显示一堆乱码,你必须重新用BINARY模式传。

对于第二种情况,是因为有很多ftp服务器和客户端软件能自动识别文件类型,并采取相应的传输方式。ftp是应用层协议,和具体操作系统无关  .
        ASCII模式和BINARY模式的区别是回车换行的处理,binary模式不对数据进行任何处理,asci模式将回车换行转换为本机的回车字符,比如Unix下是\n,Windows下是\r\n,Mac下是\r

截图:

代码:

 

  1. #!/usr/bin/env python
  2.  
  3. from ftplib import FTP
  4.  
  5.  
  6.  
  7. def ascii(site, route, filename):
  8.     def writeline(data):
  9.         fd.write(data + "\n")
  10.     f = FTP(site)
  11.     f.login()
  12.     f.cwd(route)
  13.     fd = open(filename, 'wt')
  14.     f.retrlines('RETR %s' % filename, writeline)
  15.     print "Done"
  16.     fd.close()
  17.     f.quit()
  18.  
  19. def binary(site, route, filename):
  20.     f = FTP(site)
  21.     f.login()
  22.     f.cwd(route)
  23.     fd = open(filename, 'wb')
  24.     f.retrbinary('RETR %s' % filename, fd.write)
  25.     print "Done"
  26.     fd.close()
  27.     f.quit()
  28.  
  29. method = raw_input("Enter the method, ascii or binary: ")
  30. site = raw_input("Enter the site(ftp.kernel.org): ")
  31. route = raw_input("Enter the route(/pub/linux/kernel): ")
  32. filename = raw_input("Enter the filename(README; patch8.gz): ")
  33.  
  34. if method == 'ascii':
  35.     ascii(site, route, filename)
  36. else:
  37.     binary(site, route, filename)
  38.  

 

 

 

 

PT 说:
2009年9月17日 06:14

观光之……

其实多数编辑器都能良好识别各种换行符,比如vim默认对\r\n结尾的会在每行后加一个^M的标记~~

但是最白痴的是windows的记事本,对\n结尾的直接不换行,给个黑方块

Alyssa 说:
2022年12月14日 23:24

Currently in bash, the -n operator will return true if the variable is empty. However, if the variable is empty, it should return false. This is because when a variable is double quoted, it is home buyers Welder treated as a string, and an empty string is still a string. Adding quotation marks around the variable will ensure that it is treated as a string, regardless of whether or not it is empty.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter