Python代码段

2017-12-05

记录常用的Python代码段

python使用form-data方式POST数据

首先下载依赖库:

pip install requests_toolbelt

form-data.py

from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests

request_body = MultipartEncoder(
    {
        "name": "Malu",
        "age": "18"
    }
)

request_header = {
    "Content-Type": request_body.content_type
}

response_body = requests.post("localhost", data=request_body, headers=request_header)

获取命令行参数

sys.argv

import sys

def main():
    # 打印参数
    for i in range(len(sys.argv)):
        print(sys.argv[i])

if __name__ == '__main__':
    main()

输出:

# python argv1.py ag1 ag2
argv1.py
ag1
ag2

argparse

argparse 是python 3.2 新版功能,推荐使用

标准库说明:https://docs.python.org/zh-cn/3/library/argparse.html

教程:https://docs.python.org/zh-cn/3/howto/argparse.html

import argparse

def main():
    parser = argparse.ArgumentParser()
    # group = parser.add_mutually_exclusive_group() # 创建互斥参数 -v -q 只能选其一
    # group.add_argument("-v", "--verbose", action="store_true")
    # group.add_argument("-q", "--quiet", action="store_true")
    parser.add_argument("-c","--count", type=int, help="the count",default=0)
    parser.add_argument("-m","--mail", type=str, help="the email")
    args = parser.parse_args()
    print(args.count)
    print(args.mail)
    # print(args.verbose)
    # print(args.quiet)

if __name__ == '__main__':
    main()

输出:

# python argv2.py -m malu@malu.me -c 12
12
malu@malu.me

getopt

存在于标准库中,2.7也支持,文档:https://docs.python.org/zh-cn/3/library/getopt.html


import sys, getopt

def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print('test.py -i <inputfile> -o <outputfile>')
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print('test.py -i <inputfile> -o <outputfile>')
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print('输入的文件为:', inputfile)
   print('输出的文件为:', outputfile)

if __name__ == "__main__":
   main(sys.argv[1:])

输出:

# python argv5.py -i aaa.jpg -o bbb.gif
输入的文件为: aaa.jpg
输出的文件为: bbb.gif

click

Click 是 Flask 的团队 pallets 开发的优秀开源项目,它为命令行工具的开发封装了大量方法,使开发者只需要专注于功能实现。这是一个第三方库,专门为了命令行而生的非常有名的 Python 命令行模块。主页:https://palletsprojects.com/p/click/

import click

@click.command()
@click.option('--name',default='Malu',help='name 参数,非必须,有默认值')
@click.option('--count',help='count 参数',type=int)
@click.option('--mail',help='mail 参数')
def test_for_sys(name, count, mail):
    print('the name is', name)
    print('the count is', count)
    print('the mail is', mail)

def main():
    test_for_sys()

if __name__ == '__main__':
    main()

输出:

# python argv4.py --count 12 --name malu --mail malu@malu.me
the name is malu
the count is 12
the mail is malu@malu.me

argh

argh 是非标准库中的,已经不维护,主页:https://github.com/neithere/argh/

提取字符串中IP+端口格式内容

#!/usr/bin/env python
import re

def check_proxy_host(incoming_string):
    return re.findall('(\d+\.\d+\.\d+\.\d+)+[^0-9]+(\d+)', incoming_string, re.S)

if __name__ == '__main__':
    a = ' 192.161.1.3:1211 ' \
        '123.1.1.1:4123 ' \
        '20.2.2.4  24'
    b = '124.1234.124'
    a1 = check_proxy_host(a)
    b1 = check_proxy_host(b)
    print(a1)
    print(b1)

输出:

> python CheckProxy.py
[('192.161.1.3', '1211'), ('123.1.1.1', '4123'), ('20.2.2.4', '24')]
[]