python常用的模块开发脚本

目录

标准注释

与linux交互

连接MySQL等数据库

Tkinter基础框架

SQL查询结果excel导出

调用windows程序

ping网络

图形化统计分析

匿名函数&不定量元素输入

pandas常用方法

爬虫,王者荣耀皮肤爬取


  • 标准注释

# -*- coding: UTF-8 -*-
##########################################################################
# SCRIPT_NAME     : FindStation.py
# CREATE_TIME     : 2020/03/02
# AUTHOR          : Mochou
# DESCRIBETION    : make station's find get easy
# PARAMETER       : need input station
# UPDATE_RECORD   : change run_way from write to input and kill some bugs
#
# DATE      OPERATION       CZR         DESCRIBETION              
# ________  _____________   ________    __________________________________
#
# 2020/03/02  UPDATE Mochou  
##########################################################################
  • 与linux交互

import paramiko

# 创建SSHClient实例对象
ssh = paramiko.SSHClient()
# 调用方法,标识没有远程机器的公钥,允许访问
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接远程机器 地址端口用户名密码
ssh.connect("192.168.1.24",22,"root","hhyjksfzx")
# 执行命令
#ssh.exec_command('echo $?')
stdin,stdout,stderr = ssh.exec_command('date +"%Y%m%d"')
print(stdout.read())
ssh.close()
  • 连接MySQL等数据库

  • 其他数据库格式与之一样,import包不同而已,比如sqlserver是pymssql
from pymysql import connect

def exeSqlRes(server,user,password,database,sql):
    
    conn = connect(server,user,password,database) 
    cursor = conn.cursor()    
    cursor.execute(sql)    
    list1 = cursor.fetchall()
    # get count
    try:
        print("业务日期  :%s\n收费总金额:%s\n" % (list1[0][0],list1[0][1]))  
    except:
        print("日期选择错误,请确认该天有数据\n")
    conn.close()
exeSqlRes('xx.xx.xx.xx','xx','xx','xxx','select now()')
  • Tkinter基础框架

from tkinter import *
import tkinter.font as tf

def btn_click():
    text.insert(INSERT,("输入错误,请确定输入值!\n"))

def specialType():
    # 调整字体高亮
    ft = tf.Font(family='微软雅黑',size=10) 
    text.tag_config('tag',foreground = 'blue',background='pink',font = ft)
    text.insert(INSERT,"您选择的是特情码字典,查询结果如下:\n",'tag')
      
# enter调用
def btn_click_enter(self):
    btn_click()

# 清空消息 
def cleartext():
    text.delete('0.0', END)
    
# 创建窗口对象的背景色
root = Tk()
root.title('便捷式一键查询服务系统')
root.geometry('960x700')

# Frame为布局函数
main_frame = Frame(root)
text_frame = Frame(main_frame)
station_frame = Frame(main_frame)
botton_frame = Frame(station_frame)
# 建立列表 
l1 = Label(station_frame,text='输入门架,站码,IP,互通,厂商或相关拼音')
#l2 = Label(station_frame,text='')
ipText=Entry(station_frame)
# 字体显示
# ft = tkFont.Font(family='Fixdsys', size=10, weight=tkFont.BOLD)
# pack是加载到窗口
l1.pack(side='left')
ipText.pack(side='left')
ipText['width']=24
#l2.pack(side='left')
'''
两个函数的意义是既能enter运行,又可以点击运行,方便操作,扩大使用
bind绑定enter键
注意里面是return 而不是enter
'''
b = Button(station_frame,text='查询',command=btn_click)
b['width']=4
b['height']=1
b.pack(side='left')
ipText.bind("<Return>", btn_click_enter)

# 消息输入界面
text = Text(text_frame,width = 130, height= 39)
text.pack()
main_frame.pack()
c = Button(text='清空',command=cleartext)
c['width']=4
c['height']=1
c.pack(side='left')
# 第二个函数
d = Button(text='导出excel',command=excelExport)
d['width']=8
d['height']=1
d.pack(side='top')
# 输入框的位置
station_frame.pack(side='top',pady='10')
text_frame.pack()
# 进入消息循环
root.mainloop()
  • SQL查询结果excel导出

import xlwt
import os

def excelExport():
    path1 = os.getcwd()
    excel_file = '%s\\门架基础信息数据表' % (path1)
    #判断文件是否存在
    if os.path.exists(excel_file):
        os.remove(excel_file)
    else:
        pass
    wb = xlwt.Workbook(encoding='utf-8')
    # 创建sheet,覆盖
    ws = wb.add_sheet('门架基础信息筛选表')
    # 行数
    row_num = 0
    font_style = xlwt.XFStyle()
    # 二进制
    font_style.font.bold = True
    # 表头内容
    columns = ['互通1','互通2','门架','工控机IP','站名','服务器IP','方向','属性','flag1','vplr','rsu','管理处','桩号']
    # 写进表头内容
    for col_num in range(len(columns)):
        ws.write(row_num, col_num, columns[col_num], font_style)
        font_style = xlwt.XFStyle()  # 将列名加粗后重新设置
    # list1是与columns同等长度的二维列表,可以是sql的查询结果,也可以是自身apeend
    for row in list1:
        row = ['' if i == 'nan' else i for i in row]  # 如果某项为nan则设置为空
        row_num += 1
        # 逐行写入Excel
        for col_num in range(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)
    wb.save(r'%s.xls' % excel_file) 
    list1.clear()
  • 调用windows程序

import os as os
import codecs

class EasyStation:
    # 读取站名,类型强转
    num1 = int(input("请输入数字站码: "))
    dict1 = {1111:['test1','xx.xx.xx.xx'],1113:['test2','xx.xx.xx.xx']}

    # 对错误站名做异常处理
    try:
        servername = dict1[num1][0]
        dbip = dict1[num1][1]
        file1 = "foo.txt"
        if os.path.exists(file1):
            print ("file have been existed , del firstly")
            os.remove(file1) 
        else:
            with codecs.open(file1,'w',encoding='utf-8') as f:
                f.write(u"[serverinfo]\nserverNum=1\nnum1=" + str(num1) + "\n" + "[")
                   
        # 启动
        def open_app(app_dir):
            os.startfile(app_dir)
        if __name__ == "__main__":
            app_dir = r'D:\Program Files (x86)\Youdao\YoudaoNote\YoudaoNote.exe'
            open_app(app_dir)
 
    except KeyError:
        print ("Error:未找到该站名,请查证")
  • ping网络

import re
import subprocess

def run(str_ip): 
    ftp_ret = subprocess.Popen('ping %s -n 3' % str_ip,stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
    ret = ftp_ret.stdout.read()  
    # 这里的字符集一定是gbk,否则会报错
    str_ret = ret.decode("gbk")  
    ret_s = re.search("TTL",str_ret)
    if ret_s:
        print('net succ!')
    else:
        print('net error!')
run('www.baidu.com')
  • 图形化统计分析

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from pylab import *

mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
# 导入数据
sj=['00','01','02','03','04','05','06','18','19','20','21','22','23']
#sj = filter(lambda x:x%200 == 0, zl)
sp1 = [103.00,102.50,104.50,104.00,105.00,104.00,107.50,101.00,100.00,102.00,100.50,103.50,104.50]
sp2 = [105.11,105.89,106.22,105.11,105.00,105.78,105.11,95.44,95.56,97.11,101.00,102.00,103.44]
#开始画图
plt.title('醒目工程安装前后对比图')
plt.plot(sj, sp1, color='red', label='安装前1车道车速')
plt.plot(sj, sp2, color='green', label='安装后1车道车速')
plt.legend() # 显示图例
plt.xlabel('小时')
plt.ylabel('车速')
#plt.savefig("temp1.jpg")
plt.show()
  • 匿名函数&不定量元素输入

def test(a,*b):
    print(a,end = ' ')
    for i in b:
        func = lambda i : i * 2
        print(func(i),end = ' ')
test(1,2,3,4,5,6,7)
  • pandas常用方法

pandas传送门,是的我在推销我自己

  • 爬虫,王者荣耀皮肤爬取

import os
import requests

url = 'https://pvp.qq.com/web201605/js/herolist.json'
herolist = requests.get(url)  # 获取英雄列表json文件
herolist_json = herolist.json()  # 转化为json格式
hero_name = list(map(lambda x: x['cname'], herolist.json()))  # 提取英雄的名字
hero_number = list(map(lambda x: x['ename'], herolist.json()))  # 提取英雄的编号
# 下载图片
def downloadPic():
    i = 0
    for j in hero_number:
        # 创建文件夹
        os.mkdir("C:\\Users\\dtboy\\Desktop\\downWz\\" + hero_name[i])
        # 进入创建好的文件夹
        os.chdir("C:\\Users\\dtboy\\Desktop\\downWz\\" + hero_name[i])
        i += 1
        for k in range(10):
            # 拼接url
            onehero_link = 'http://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/' + str(j) + '/' + str(j) + '-bigskin-' + str(k) + '.jpg'
            im = requests.get(onehero_link)  # 请求url
            if im.status_code == 200:
                open(str(k) + '.jpg', 'wb').write(im.content)  # 写入文件
downloadPic()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章