标签 python 下的文章

用python生成golang支持的所有交叉编译环境脚本

虽然标题有些奇葩,但是对于我这个强迫症来说,每次golang版本更新,第一件事就是把常见的交叉编译环境给弄好,每次都写也挺麻烦,再加上随着golang版本的升级,支持的GOARCH和GOOS也不断的变多,也懒得去查wiki或者手册,就直接用下面的代码生成吧

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

__author__ = 'Chungpei Wang'
import os
import json

if __name__ == '__main__':
    env_dist = os.environ
    goroot = env_dist['GOROOT']
    gocmd = os.path.join(goroot, "bin", "go")
    result = os.popen(gocmd + " tool dist list -json")
    strresult = result.read()
    jsonresult = json.loads(strresult)
    shell_content = "#!/bin/bash" + os.linesep * 2 + "export CGO_ENABLED=0" + os.linesep * 2
    # 仅仅是因为强迫症,按照GOARCH进行排序,这样看起来整齐点
    jsonresult.sort(key=lambda k: (k.get('GOARCH', 0)))
    for data in jsonresult:
        shell_content += "export GOARCH=" + data['GOARCH'] + os.linesep
        shell_content += "export GOOS=" + data['GOOS'] + os.linesep
        shell_content += "./make.bash --no-clean" + os.linesep
        shell_content += os.linesep
    print(shell_content)

即:

1.先从系统环境变量中获取到$GOROOT
2.再执行$GOROOT/bin/go tool list list -json,获取对应版本golang所支持的所有GOARCH和GOOS
3.依次export GOARCH、GOOS,并执行make.bash(windows下应该改为make.bat)

tornado微信公众号

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

__author__ = 'tan9le'

import os
from wechatpy import parse_message, create_reply
from wechatpy.utils import check_signature
from wechatpy.exceptions import (
    InvalidSignatureException,
)
import schedule
from datetime import timedelta
import tornado.wsgi
from tornado.options import define, options

TOKEN = os.getenv('WECHAT_TOKEN', '填写token')
AES_KEY = os.getenv('WECHAT_AES_KEY', '填写EncodingAESKey(消息加解密密钥)')
APPID = os.getenv('WECHAT_APPID', '填写AppID(应用ID)')

define("port", default=8000, help="run on the given port", type=int)
class WeiXinHandler(tornado.web.RequestHandler):
    #用于微信公众号网页修改基本信息时的验证
    def get(self):
        # 获取微信公众平台发送的验证参数
        signature = self.get_argument('signature', '')
        timestamp = self.get_argument('timestamp', '')
        nonce = self.get_argument('nonce', '')
        echostr = self.get_argument('echostr', '')
        try:
            check_signature(TOKEN, signature, timestamp, nonce)
        except InvalidSignatureException:
            self.set_stauts('403')
            self.write('error,code 403')
        #按照约定,如果正常,则原样返回echostr
        self.write(echostr)
    def post(self):
        # 获取微信公众平台发送的验证参数
        signature = self.get_argument('signature', '')
        timestamp = self.get_argument('timestamp', '')
        nonce = self.get_argument('nonce', '')
        echostr = self.get_argument('echostr', '')
        # 获取所有值并解析
        msg = parse_message(self.request.body)
        if msg.type == 'text':
            content = msg.content.strip()
            
            reply = create_reply(content, msg)
            self.write(reply.render())
        else:
            help_str = "目前仅支持文字输入\n"
            reply = create_reply(help_str, msg)
            self.write(reply.render())




app = tornado.wsgi.WSGIApplication([
    # 这里需要根据修改为自己的URL匹配
    (r"/", WeiXinHandler),

])

if __name__=="__main__":
    # 启动tornado实例
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

然后使用

python main.py --port=8000

就可以启动应用啦
依赖:

tornado
wechatpy

解决Python 3.6使用pip时Unable to locate finder for pip._vendor.distlib的问题

最近在笔记本上安装了Python 3.6 x86-64位版本,习惯性的创建了一个virtualenv,然后使用pip安装第三库的时候发生以下错误:

Collecting virtualenv
  Downloading virtualenv-15.0.3-py2.py3-none-any.whl (3.5MB)
    100% |████████████████████████████████| 3.5MB 256kB/s
Installing collected packages: virtualenv
Exception:
Traceback (most recent call last):
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\commands\install.py", line 317, in run
    prefix=options.prefix_path,
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 742, in install
    **kwargs
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 831, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files
    isolated=self.isolated,
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\wheel.py", line 493, in move_wheel_files
    maker.make_multiple(['%s = %s' % kv for kv in console.items()])
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 383, in make_multiple
    filenames.extend(self.make(specification, options))
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 372, in make
    self._make_script(entry, filenames, options=options)
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 276, in _make_script
    self._write_script(scriptnames, shebang, script, filenames, ext)
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 212, in _write_script
    launcher = self._get_launcher('t')
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\scripts.py", line 351, in _get_launcher
    result = finder(distlib_package).find(name).bytes
  File "c:\users\corey shaw\appdata\local\programs\python\python36\lib\site-packages\pip\_vendor\distlib\resources.py", line 324, in finder
    raise DistlibException('Unable to locate finder for %r' % package)
pip._vendor.distlib.DistlibException: Unable to locate finder for 'pip._vendor.distlib'

解决方案如下:
1.激活对应的virtualenv,然后执行:

python -m pip uninstall pip setuptools

2.下载

https://bootstrap.pypa.io/get-pip.py

3.同样在virtualenv激活状态下,执行python get-pip.py,这里要注意路径的问题,很可能路径没配置,导致了把原有python进行了pip卸载重装的动作

Python某系统登录后自动提交

自己能看懂就行 ^_^

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = 'tan9le'

import requests
import datetime
import random

host = '服务器地址+端口'
Origin = 'http://服务器地址+端口/'
indexURL = Origin + 'attp/www/index.html'
loginURL = Origin + 'attp/login/login.do'
operURL = Origin + 'attp/attendance/entryForJsp'
user_name = '用户名'
password = '密码'

today = datetime.date.today()
working_days = ['2016-09-17','2016-10-08','2016-10-09']
holidays = ['2016-10-03','2016-10-04','2016-10-04','2016-10-06','2016-10-07']

#通用header
header_base = {
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
    'Host': host,
    'Origin':Origin,
    'Connection':'keep-alive',
    'Referer':indexURL
}
#登录时引用的header
loginHeader = header_base.copy()
loginHeader["Content-Type"] = 'application/json;charset=UTF-8'
#操作时引用的header
operHeader = header_base.copy()

#全局request session,用来解决重复请求时的session、cookeis问题
s = requests.session()

def init():
    #得到日期对应的字符串
    todaystr = today.strftime("%Y-%m-%d")
    #得到日期是星期几,0代表周一
    dayofweek = today.weekday()
    #判断是否应该打卡
    if dayofweek < 6:
        if(todaystr in holidays):
            operflag = False
            print("工作日放假^_^")
        else:
            operflag = True
            print("正常上班,需要打卡")
    else:
        if(todaystr in working_days):
            operflag = True
            print("周末正常上班,需要打卡")
        else:
            operflag = False
            print("周末正常休息^_^")
    return operflag

#登录请求
def login():
    loginHeader['request-type'] = 'angular/api'
    login_param = {"login_id":user_name,"password":password,"roleType":"0"}
    #登录
    s.headers = loginHeader
    s.post(loginURL,json=login_param)
    #访问初始界面
    r = s.get(Origin + 'attp/attendance/initPage')
    #登录成功后,将header还原
    s.headers = header_base
    return r

#出勤
def chuqin(yearmonth,begin_time):
    operHeader['Referer'] = Origin + 'attp/attendance/initAttForJsp'
    oper_param = {"staff_code":user_name,"yearmonth":yearmonth,"project_id":"-1","projectname":" ","projectcode":"-1","area_id":"南京市","actualArea":"江苏省 南京市","create_user":user_name,"begin_time":begin_time}
    s.headers = operHeader
    r = s.post(operURL, json=oper_param)
    # 操作成功后,将header还原
    s.headers = header_base
    return r

#退勤
def tuiqin(yearmonth,end_time):
    operHeader['Referer'] = Origin + 'attp/attendance/initAttForJsp'
    oper_param = {"staff_code":user_name,"yearmonth":yearmonth,"project_id":"-1","projectname":" ","projectcode":"-1","area_id":"南京市","actualArea":"江苏省 南京市","create_user":user_name,"end_time":end_time}
    s.headers = operHeader
    r = s.post(operURL, json=oper_param)
    # 操作成功后,将header还原
    s.headers = header_base
    return r

#获取HH:MM样式的随机时间
def randmontime(beginHH,endHH,beginMM,endMM):
    HH = random.randint(beginHH, endHH)
    MM = random.randint(beginMM, endMM)
    if(HH<10):
        HHstr = '0' + str(HH)
    else:
        HHstr = str(HH)
    if (MM < 10):
        MMstr = '0' + str(MM)
    else:
        MMstr = str(MM)
    return HHstr + ':' + MMstr

if __name__ == '__main__':
    flag = init()
    print(flag)
    if flag:
        todaystr = today.strftime("%Y-%m-%d")
        chuqintime = randmontime(7,8,15,45)
        tuiqintime = randmontime(19,20,30,59)
        login()
        print(chuqin(todaystr,chuqintime).text)
        print(tuiqin(todaystr,tuiqintime).text)

自动登录深信服上网认证控制

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
import requests

if __name__ == '__main__':
    session = requests.session()

    base_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.71 Safari/537.36 OPR/35.0.2066.23 (Edition beta)', 'Referer': 'http://blog.bbzhh.com'}
    session.headers = base_headers
    resp = session.post('http://深信服认证主机IP/webAuth/',{'username':'用户名','password':'密码','rememberPwd':'1','pwd':'密码','secret':'true'})
    print unicode(resp.text).encode('utf8')