1.client.getPage 返回一個defer。 是異步的。python
#coding:utf8
from twisted.internet import reactor
from twisted.web import client
IP="202.102.224.68"
def print_fun(x):
print x
def run():
defer=client.getPage("http://freeapi.ipip.net/"+IP)
defer.addCallback(lambda x:print_fun(x))
reactor.callLater(2,run)
run()
reactor.run()
python test.py運行便可
爲了可以後臺運行此程序 ,能夠經過以下方式:
#coding:utf8
from twisted.internet import reactor
from twisted.web import client
from twisted.application.service import Application
IP="202.102.224.68"
def print_fun(x):
print x
def run():
defer=client.getPage("http://freeapi.ipip.net/"+IP)
defer.addCallback(lambda x:print_fun(x))
reactor.callLater(2,run)
run()
application=Application("test")
twistd -y test.py運行便可。 其會直接後臺運行。並在當前目錄生成twistd.log twistd.pid文件。 程序的print輸出都被寫入到了twisd.log中
[root@zkp534 testfiledir]# tail -f twistd.logreact
2016-07-07 16:57:33+0800 [-] ["中國","河南","鄭州","","聯通"]web
2016-07-07 16:57:33+0800 [HTTPPageGetter,client] Stopping factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>api
2016-07-07 16:57:33+0800 [-] ["中國","河南","鄭州","","聯通"]app
2016-07-07 16:57:33+0800 [HTTPPageGetter,client] Stopping factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>異步
2016-07-07 16:57:33+0800 [-] Starting factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>.net
2016-07-07 16:57:35+0800 [-] Starting factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>ip
2016-07-07 16:57:36+0800 [-] ["中國","河南","鄭州","","聯通"]get
2016-07-07 16:57:36+0800 [HTTPPageGetter,client] Stopping factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>pip
2016-07-07 16:57:37+0800 [-] Starting factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>
2016-07-07 16:57:39+0800 [-] Starting factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>
2016-07-07 16:57:41+0800 [-] Starting factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>
2016-07-07 16:57:42+0800 [-] ["中國","河南","鄭州","","聯通"]
2016-07-07 16:57:42+0800 [HTTPPageGetter,client] Stopping factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>
2016-07-07 16:57:43+0800 [-] Starting factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>