python
python学习笔记

python更新库

  1. 查看哪些库有新版本

    pip list --outdated

  2. 更新命令

    pip install --upgrade 库名

python检查字符串在另一个文件中是否存在

pretxt0 = ('oa', 'ob', 'oc', 'od', 'oe', 'of', 'og', 'oh', 'oi', 'oj', 'ok', 'ol', 'om', 'on', 'oo', 'op', 'oq', 'or', 'os', 'ot', 'ou', 'ov', 'ow', 'ox', 'oy', 'oz')
for pretxt in pretxt0:
    doc = open (pretxt + '.txt','w')
    aa = ["aa.cn", "ab.cn", "zv.cn", "zw.cn", "zx.cn", "zy.cn", "zz.cn"]
    with open('domain_cn_' + pretxt + '.txt','r') as foo:
        doo = foo.readlines()
        for ab in aa:
            a = 'Domain Name: ' + pretxt + ab + '\n'
            if a not in doo: 
                print (pretxt + ab,file = doc)
    doc.close()

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

print输出多个变量时不要空格

print输出多个变量时不要空格

a = "Hello"
b = "World"
print (a,b)  //输出 Hello World
print(a,b,sep='')  //输出 HelloWorld

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)