reactorpython
① python zipfile 把整个文件夹内的文件打包 没有生成.zip文件
- 如果操作系统为 Windows 7 请先 "以管理员身份运行" cmd.exe
cmd.exe 在 C:WindowsSystem32 文件夹下。
#!/usr/bin/python
#coding:utf-8
importos
importsys
importzipfile
path='e:\pythonWorkSpace\practice'
zipfilename='e:\version.zip'
#pathisadireactoryornot.
ifnotos.path.isdir(path):
printpath+'Nosuchadireactory'
exit()
ifos.path.exists(zipfilename):
#zipfilenameisexist.Append.
print'Addfilesinto'+zipfilename
zipfp=zipfile.ZipFile(zipfilename,'a',zipfile.ZIP_DEFLATED)
fordirpath,dirnames,filenamesinos.walk(path,True):
forfilanameinfilenames:
direactory=os.path.join(dirpath,filaname)
print'Add...'+direactory
zipfp.write(direactory)
else:
#zipfilenameisnotexist.Create.
print'Createnewfile'+zipfilename
zipfp=zipfile.ZipFile(zipfilename,'w',zipfile.ZIP_DEFLATED)
fordirpath,dirnames,filenamesinos.walk(path,True):
forfilanameinfilenames:
direactory=os.path.join(dirpath,filaname)
print'Compress...'+direactory
zipfp.write(direactory)
#.
zipfp.close()
② 在cmd中运行python程序报错no such file or direactory
-
如果操作系统为
Windows
7
请先
"以管理员身份运行"
cmd.exe
cmd.exe
在
C:\Windows\System32
文件夹下。
-
先试试:
dir
Python文件全路径名
如:
dir
E:\pythonWorkSpace\all.py
看看是否存在文件
'all.py'。
如果文件存在
-
再试试:
Python2.7.5可执行文件全路径名
Python文件全路径名
如:
C:\Python27\python.exe
E:\pythonWorkSpace\all.py
③ python 每隔一秒循环发10条数据 为什么是10条一起发出去的
importtime
fromtwisted.internetimportprotocol,reactor,defer,threads
classEcho(protocol.Protocol):
defconnectionMade(self):
#1.writeSomeData
defwriteSomeData():
i=10
whilei:
self.transport.writeSomeData(time.strftime('%H:%M:%S',time.localtime(time.time())))
self.transport.writeSomeData(' ')
time.sleep(2)
i-=1
writeSomeData()
#2,threads.deferToThread
defwrite():
i=10
whilei:
self.transport.write(time.strftime('%H:%M:%S',time.localtime(time.time())))
self.transport.write(' ')
time.sleep(2)
i-=1
threads.deferToThread(write)
classEchoFactory(protocol.Factory):
defbuildProtocol(self,addr):
returnEcho()
reactor.listenTCP(8000,EchoFactory())
reactor.run()
写了两种方法writeSomeData,deferToThread
④ 这个提示是不是twisted框架没有安装好
要下一个zope.interface装,google一下网上有
⑤ Python核心编程的图书目录
第1部分Python核心
第1章欢迎来到Python世界
第2章快速入门
第3章Python基础
第4章Python对象
第5章数字
第6章序列:字符串、列表和元组
第7章映像和集合类型
第8章条件和循环
第9章文件和输入输出
第10章错误和异常
第11章函数和函数式编程
第12章模块
第13章面向对象编程
第14章执行环境
第2部分高级主题
第15章正则表达式
15.1引言/动机
15.2正则表达式使用的特殊符号和字符
15.2.1用管道符号(|)匹配多个正则表达式模式
15.2.2匹配任意一个单个的字符(.)
15.2.3从字符串的开头或结尾或单词边界开始匹配(^/$ / /B )
15.2.4创建字符类([])
15.2.5指定范围(-)和否定(^)
15.2.6使用闭包操作符(*,+,?,{})实现多次出现/重复匹配
15.2.7特殊字符表示、字符集
15.2.8用圆括号(())组建组
15.3正则表达式和Python语言
15.3.1re模块:核心函数和方法
15.3.2使用compile()编译正则表达式
15.3.3匹配对象和group()、groups()方法
15.3.4用match()匹配字符串
15.3.5search()在一个字符串中查找一个模式(搜索与匹配的比较)
15.3.6匹配多个字符串(|)
15.3.7匹配任意单个字符(.)
15.3.8创建字符集合([])
15.3.9重复、特殊字符和子组
15.3.10从字符串的开头或结尾匹配及在单词边界上的匹配
15.3.11用findall()找到每个出现的匹配部分
15.3.12用sub()(和subn())进行搜索和替换
15.3.13用split()分割(分隔模式)
15.4正则表达式示例
15.4.1匹配一个字符串
15.4.2搜索与匹配的比较,“贪婪”匹配
15.5练习
第16章网络编程
16.1引言
16.1.1什么是客户端/服务器架构
16.1.2客户端/服务器网络编程
16.2套接字:通信端点
16.2.1什么是套接字
16.2.2套接字地址:主机与端口
16.2.3面向连接与无连接
16.3Python中的网络编程
16.3.1socket()模块函数
16.3.2套接字对象(内建)方法
16.3.3创建一个TCP服务器
16.3.4创建TCP客户端
16.3.5运行我们的客户端与TCP服务器
16.3.6创建一个UDP服务器
16.3.7创建一个UDP客户端
16.3.8执行UDP服务器和客户端
16.3.9Socket模块属性
16.4*SocketServer模块
16.4.1创建一个SocketServerTCP服务器
16.4.2创建SocketServerTCP客户端
16.4.3执行TCP服务器和客户端
16.5Twisted框架介绍
16.5.1创建一个Twisted Reactor TCP服务器
16.5.2创建一个Twisted Reactor TCP客户端
16.5.3执行TCP服务器和客户端
16.6相关模块
16.7练习
第17章网络客户端编程
17.1什么是因特网客户端
17.2文件传输
17.2.1文件传输网际协议
17.2.2文件传输协议(FTP)
17.2.3Python和FTP
17.2.4ftplib.FTP类方法
17.2.5交互式FTP示例
17.2.6客户端FTP程序举例
17.2.7FTP的其他方面
17.3网络新闻
17.3.1Usenet与新闻组
17.3.2网络新闻传输协议(NNTP)
17.3.3Python和NNTP
17.3.4nntplib.NNTP类方法
17.3.5交互式NNTP举例
17.3.6客户端程序NNTP举例
17.3.7NNTP的其他方面
17.4电子邮件
17.4.1电子邮件系统组件和协议
17.4.2发送电子邮件
17.4.3Python和SMTP
17.4.4smtplib.SMTP类方法
17.4.5交互式SMTP示例
17.4.6SMTP的其他方面
17.4.7接收电子邮件
17.4.8POP和IMAP
17.4.9Python和POP3
17.4.10交互式POP3举例
17.4.11poplib.POP3类方法
17.4.12客户端程序SMTP和POP3举例
17.5相关模块
17.5.1电子邮件
17.5.2其他网络协议
17.6练习
第18章多线程编程
18.1引言/动机
18.2线程和进程
18.2.1什么是进程
18.2.2什么是线程
18.3Python、线程和全局解释器锁
18.3.1全局解释器锁(GIL)
18.3.2退出线程
18.3.3在Python中使用线程
18.3.4没有线程支持的情况
18.3.5Python的threading模块
18.4thread模块
18.5threading模块
18.5.1Thread类
18.5.2斐波那契、阶乘和累加和
18.5.3threading模块中的其他函数
18.5.4生产者-消费者问题和Queue模块
18.6相关模块
18.7练习
第19章图形用户界面编程
19.1简介
19.1.1什么是Tcl、Tk和Tkinter
19.1.2安装和使用Tkinter533
19.1.3客户端/服务器架构534
19.2Tkinter与Python编程534
19.2.1Tkinter模块:把Tk引入你的程序
19.2.2GUI程序开发简介
19.2.3顶层窗口:
19.2.4Tk组件
19.3Tkinter举例
19.3.1标签组件
19.3.2按钮组件
19.3.3标签和按钮组件
19.3.4标签、按钮和进度条组件
19.3.5偏函数应用举例
19.3.6中级Tkinter范例
19.4其他GUI简介
19.4.1Tk Interface eXtensions (Tix)
19.4.2Python MegaWidgets (PMW)
19.4.3wxWidgets和wxPython
19.4.4GTK+和PyGTK
19.5相关模块和其他GUI
19.6练习
第20章Web编程
20.1介绍
20.1.1Web应用:客户端/服务器计算
20.1.2因特网
20.2使用Python进行Web应用:创建一个简单的Web客户端
20.2.1统一资源定位符
20.2.2urlparse模块
20.2.3urllib模块
20.2.4urllib2模块
20.3高级Web客户端
20.4CGI:帮助Web服务器处理客户端数据
20.4.1CGI介绍
20.4.2CGI应用程序
20.4.3cgi模块
20.5建立CGI应用程序
20.5.1建立Web服务器
20.5.2建立表单页
20.5.3生成结果页
20.5.4生成表单和结果页面
20.5.5全面交互的Web站点
20.6在CGI中使用Unicode编码
20.7高级CGI
20.7.1Mulitipart表单提交和文件的上传
20.7.2多值字段
20.7.3cookie
20.7.4使用高级CGI
20.8Web(HTTP)服务器
20.9相关模块
20.10练习
第21章数据库编程
21.1介绍
21.1.1持久存储
21.1.2基本的数据库操作和SQL语言
21.1.3数据库和Python
21.2Python数据库应用程序程序员接口(DB-API)
21.2.1模块属性
21.2.2连接对象
21.2.3游标对象
21.2.4类型对象和构造器
21.2.5关系数据库
21.2.6数据库和Python:接口程序
21.2.7使用数据库接口程序举例
21.3对象-关系管理器(ORM)
21.3.1考虑对象,而不是SQL
21.3.2Python和ORM
21.3.3雇员数据库举例
21.3.4总结
21.4相关模块
21.5练习
第22章扩展Python623
22.1引言/动机
22.1.1什么是扩展
22.1.2为什么要扩展Python
22.2创建Python扩展
22.2.1创建您的应用程序代码
22.2.2用样板来包装你的代码
22.2.3编译
22.2.4导入和测试
22.2.5引用计数
22.2.6线程和全局解释器锁(GIL)
22.3相关话题
22.4练习
第23章其他话题
23.1Web服务
23.2用Win32的COM来操作微软Office
23.2.1客户端COM编程
23.2.2 微软Excel
23.2.3微软Word第1部分Python核心
23.2.4微软PowerPoint
23.2.5微软Outlook
23.2.6中等规模的例子
23.3用Jython写Python和Java的程序
23.3.1什么是Jython
23.4练习
23.2.4微软PowerPoint
23.2.5微软Outlook
23.2.6中等规模的例子
23.3用Jython写Python和Java的程序
23.3.1什么是Jython
23.3.2Swing GUI开发(Java或者Python!)
23.4练习
⑥ Python安装Scrapy出现以下错误怎么办
itcast@itcast:~/pachong$ scrapy
Traceback (most recent call last):
File "/usr/local/bin/scrapy", line 7, in <mole>
from scrapy.cmdline import execute
File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 9, in <mole>
from scrapy.crawler import CrawlerProcess
File "/usr/local/lib/python2.7/dist-packages/scrapy/crawler.py", line 6, in <mole>
from twisted.internet import reactor, defer
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/reactor.py", line 38, in <mole>
from twisted.internet import default
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/default.py", line 56, in <mole>
install = _getInstallFunction(platform)
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/default.py", line 44, in _getInstallFunction
from twisted.internet.epollreactor import install
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/epollreactor.py", line 24, in <mole>
from twisted.internet import posixbase
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/posixbase.py", line 18, in <mole>
from twisted.internet import error, udp, tcp
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/tcp.py", line 28, in <mole>
from twisted.internet._newtls import (
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/_newtls.py", line 21, in <mole>
from twisted.protocols.tls import TLSMemoryBIOFactory, TLSMemoryBIOProtocol
File "/usr/local/lib/python2.7/dist-packages/twisted/protocols/tls.py", line 63, in <mole>
from twisted.internet._sslverify import _setAcceptableProtocols
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/_sslverify.py", line 38, in <mole>
TLSVersion.TLSv1_1: SSL.OP_NO_TLSv1_1,
AttributeError: 'mole' object has no attribute 'OP_NO_TLSv1_1'
⑦ 在cmd中运行python程序报错no such file or direactory
- 如果操作系统为 Windows 7 请先 "以管理员身份运行" cmd.exe
cmd.exe 在 C:\Windows\System32 文件夹下。
- 先试试:
dir Python文件全路径名
如:
dir E:\pythonWorkSpace\all.py
看看是否存在文件 'all.py'。
如果文件存在
- 再试试:
Python2.7.5可执行文件全路径名 Python文件全路径名
如:
C:\Python27\python.exe E:\pythonWorkSpace\all.py
⑧ python的计时器
你可以用Twisted来实现,源代码如下:
from twisted.internet import task
from twisted.internet import reactor
#set global variables
g = 0
def run():
global g
g = g + 1
print 'the global value g is:%s'%g
#add function run to twisted's looping call
l = task.LoopingCall(run)
#set interval to 5*60 seconds
l.start(5*60)
reactor.run()
要运行这段代码你得装twisted和zope中关于interface的定义,上google搜搜载一个装了就可以了。
⑨ python打包工具 生成文件在哪
如果操作系统为 Windows 7 请先 "以管理员身份运行" cmd.exe
cmd.exe 在 C:\Windows\System32 文件夹下。
#! /usr/bin/python
#coding: utf-8
import os
import sys
import zipfile
path = 'e:\\pythonWorkSpace\\practice'
zipfilename = 'e:\\version.zip'
# path is a direactory or not.
if not os.path.isdir(path):
print path + ' No such a direactory'
exit()
if os.path.exists(zipfilename):
# zipfilename is exist.Append.
print 'Add files into ' + zipfilename
zipfp = zipfile.ZipFile(zipfilename, 'a' ,zipfile.ZIP_DEFLATED)
for dirpath, dirnames, filenames in os.walk(path, True):
for filaname in filenames:
direactory = os.path.join(dirpath,filaname)
print 'Add... ' + direactory
zipfp.write(direactory)
else:
# zipfilename is not exist.Create.
print 'Create new file ' + zipfilename
zipfp = zipfile.ZipFile(zipfilename, 'w' ,zipfile.ZIP_DEFLATED)
for dirpath, dirnames, filenames in os.walk(path, True):
for filaname in filenames:
direactory = os.path.join(dirpath,filaname)
print 'Compress... ' + direactory
zipfp.write(direactory)
# Flush and Close zipfilename at last.
zipfp.close()
⑩ 如何使用python爬虫jfinal
一、gzip/deflate支持
现在的网页普遍支持gzip压缩,这往往可以解决大量传输时间,以VeryCD的主页为例,未压缩版本247K,压缩了以后45K,为原来的1/5。这就意味着抓取速度会快5倍。
然而python的urllib/urllib2默认都不支持压缩,要返回压缩格式,必须在request的header里面写明’accept-
encoding’,然后读取response后更要检查header查看是否有’content-encoding’一项来判断是否需要解码,很繁琐琐
碎。如何让urllib2自动支持gzip, defalte呢?其实可以继承BaseHanlder类,然后build_opener的方式来处理:
import urllib2
from gzip import GzipFile
from StringIO import StringIO
class ContentEncodingProcessor(urllib2.BaseHandler):
"""A handler to add gzip capabilities to urllib2 requests """
# add headers to requests
def http_request(self, req):
req.add_header("Accept-Encoding", "gzip, deflate")
return req
# decode
def http_response(self, req, resp):
old_resp = resp
# gzip
if resp.headers.get("content-encoding") == "gzip":
gz = GzipFile(
fileobj=StringIO(resp.read()),
mode="r"
)
resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code)
resp.msg = old_resp.msg
# deflate
if resp.headers.get("content-encoding") == "deflate":
gz = StringIO( deflate(resp.read()) )
resp = urllib2.addinfourl(gz, old_resp.headers, old_resp.url, old_resp.code) # 'class to add info() and
resp.msg = old_resp.msg
return resp
# deflate support
import zlib
def deflate(data): # zlib only provides the zlib compress format,not the deflate format;
try: # so on top of all there's this workaround:
return zlib.decompress(data, -zlib.MAX_WBITS)
except zlib.error:
return zlib.decompress(data)然后就简单了,
encoding_support = ContentEncodingProcessor
opener = urllib2.build_opener( encoding_support, urllib2.HTTPHandler )
#直接用opener打开网页,如果服务器支持gzip/defalte则自动解压缩
content = opener.open(url).read()二、更方便地多线程
总结一文的确提及了一个简单的多线程模板,但是那个东东真正应用到程序里面去只会让程序变得支离破碎,不堪入目。在怎么更方便地进行多线程方面我也动了一番脑筋。先想想怎么进行多线程调用最方便呢?
1、用twisted进行异步I/O抓取
事实上更高效的抓取并非一定要用多线程,也可以使用异步I/O法:直接用twisted的getPage方法,然后分别加上异步I/O结束时的callback和errback方法即可。例如可以这么干:
from twisted.web.client import getPage
from twisted.internet import reactor
links = [ 'http://www.verycd.com/topics/%d/'%i for i in range(5420,5430) ]
def parse_page(data,url):
print len(data),url
def fetch_error(error,url):
print error.getErrorMessage(),url
# 批量抓取链接
for url in links:
getPage(url,timeout=5)
.addCallback(parse_page,url) #成功则调用parse_page方法
.addErrback(fetch_error,url) #失败则调用fetch_error方法
reactor.callLater(5, reactor.stop) #5秒钟后通知reactor结束程序
reactor.run()twisted人如其名,写的代码实在是太扭曲了,非正常人所能接受,虽然这个简单的例子看上去还好;每次写twisted的程序整个人都扭曲了,累得不得了,文档等于没有,必须得看源码才知道怎么整,唉不提了。
如果要支持gzip/deflate,甚至做一些登陆的扩展,就得为twisted写个新的HTTPClientFactory类诸如此类,我这眉头真是大皱,遂放弃。有毅力者请自行尝试。
这篇讲怎么用twisted来进行批量网址处理的文章不错,由浅入深,深入浅出,可以一看。
2、设计一个简单的多线程抓取类
还是觉得在urllib之类python“本土”的东东里面折腾起来更舒服。试想一下,如果有个Fetcher类,你可以这么调用
f = Fetcher(threads=10) #设定下载线程数为10
for url in urls:
f.push(url) #把所有url推入下载队列
while f.taskleft(): #若还有未完成下载的线程
content = f.pop() #从下载完成队列中取出结果
do_with(content) # 处理content内容这么个多线程调用简单明了,那么就这么设计吧,首先要有两个队列,用Queue搞定,多线程的基本架构也和“技巧总结”一文类似,push方法和
pop方法都比较好处理,都是直接用Queue的方法,taskleft则是如果有“正在运行的任务”或者”队列中的任务”则为是,也好办,于是代码如
下:import urllib2
from threading import Thread,Lock
from Queue import Queue
import time
class Fetcher:
def __init__(self,threads):
self.opener = urllib2.build_opener(urllib2.HTTPHandler)
self.lock = Lock() #线程锁
self.q_req = Queue() #任务队列
self.q_ans = Queue() #完成队列
self.threads = threads
for i in range(threads):
t = Thread(target=self.threadget)
t.setDaemon(True)
t.start()
self.running = 0
def __del__(self): #解构时需等待两个队列完成
time.sleep(0.5)
self.q_req.join()
self.q_ans.join()
def taskleft(self):
return self.q_req.qsize()+self.q_ans.qsize()+self.running
def push(self,req):
self.q_req.put(req)
def pop(self):
return self.q_ans.get()
def threadget(self):
while True:
req = self.q_req.get()
with self.lock: #要保证该操作的原子性,进入critical area
self.running += 1
try:
ans = self.opener.open(req).read()
except Exception, what:
ans = ''
print what
self.q_ans.put((req,ans))
with self.lock:
self.running -= 1
self.q_req.task_done()
time.sleep(0.1) # don't spam
if __name__ == "__main__":
links = [ 'http://www.verycd.com/topics/%d/'%i for i in range(5420,5430) ]
f = Fetcher(threads=10)
for url in links:
f.push(url)
while f.taskleft():
url,content = f.pop()
print url,len(content)