练手小程序
程序作用:对IP实时记录;
1、定时获取外网IP,存储在本地文件中;
编写思路:
1)收集获取外网的API接口
1 # -*- coding: utf-8 -*- 2 # -*- coding: gbk -*- 3 # Date: 2016/4/27 4 # Created by zh 5 6 from threading import Timer 7 import time 8 import urllib2 9 import re 10 """ 11 次数计数器 12 """ 13 timecount = 0 14 timer_interval=1 15 """ 16 记录时间 17 访问IP接口取出IP 18 写出 时间+ IP 到 IPcount+time.txt 文件中 19 """ 20 def GetIP(): 21 nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 22 response = urllib2.urlopen('https://ipip.yy.com/get_ip_info.php').read() 23 Currentip = re.search('\d+\.\d+\.\d+\.\d+',response).group(0) 24 f = open("IPcount+time.txt","a") 25 f.writelines(nowtime +" 当前的IP地址是 :" + Currentip +"\n") 26 t=Timer(timer_interval,GetIP) 27 t.start() 28 """ 29 循环执行代码 30 设定每隔一段时间取一次外网IP 31 """ 32 while True: 33 time.sleep(5) 34 GetIP() 35 timecount += timer_interval 36 print ("program run %s time" % timecount )