1.client.getPage 返回一个defer。 是异步的。
#coding:utf8from twisted.internet import reactorfrom twisted.web import clientIP="202.102.224.68"def print_fun(x):print xdef 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:utf8from twisted.internet import reactorfrom twisted.web import clientfrom twisted.application.service import ApplicationIP="202.102.224.68"def print_fun(x):print xdef 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中
[[email protected] testfiledir]# tail -f twistd.log
2016-07-07 16:57:33+0800 [-] ["中国","河南","郑州","","联通"]
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 [-] ["中国","河南","郑州","","联通"]
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>
2016-07-07 16:57:35+0800 [-] Starting factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>
2016-07-07 16:57:36+0800 [-] ["中国","河南","郑州","","联通"]
2016-07-07 16:57:36+0800 [HTTPPageGetter,client] Stopping factory <HTTPClientFactory: http://freeapi.ipip.net/202.102.224.68>
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>