Ubuntu切换python版本

Ubuntu切换python版本

  • 查看系统已安装的python版本
ls /usr/bin/python*
  • 配置可切换版本
update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
update-alternatives --install /usr/bin/python python /usr/bin/python3.5 2
  • 查看可用版本
update-alternatives --list python
/usr/bin/python2.7
/usr/bin/python3.5
  • 版本切换
update-alternatives --config python

python使用try-except处理request循环超时报错

使用request循环调用某一页面或者api时,若遇到请求超时会跳出循环停止运行,因此使用try/except来处理超时问题:

import urllib.request,re,time
url = "http://www.zhaoxugeng.cn/api/ip.php" #网页地址
while True:
    try:
        myPage=urllib.request.urlopen(url).read()
        myPage = myPage.decode('GBK')
        match = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
        line = match.findall(myPage)
        print (line[0])
        time.sleep (5)
    except:
        print ("fail")
        time.sleep (5)