小言_互联网的博客

python常用的模块开发脚本

376人阅读  评论(0)

目录

1 标准注释

2 与linux交互

3 连接MySQL等数据库

4 Tkinter基础框架

5 常用IO读写

6 SQL查询结果excel导出

7 调用windows程序

8 ping网络

9 图形化统计分析

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

11 pandas常用方法

12 PyQt多个日历时间模块加载与选择时间获取

13 for循环多个变量(zip)

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

15 python依据文件内容改文件名

16 时间的转换与计算


  • 1 标准注释


   
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. """
  4. @File : Basic010.py
  5. @Contact : dtboys***@163.com
  6. @License : (C)Copyright 1997-2020, XXXXXXXXXXXXX CO.,LTD.
  7. @Modify Time @Author @Version @Desciption
  8. ------------ ------- -------- -----------
  9. 2020/7/3 11:32 liqb 1.0 kill some bugs
  10. """
  • 2 与linux交互


   
  1. import paramiko
  2. # 创建SSHClient实例对象
  3. ssh = paramiko.SSHClient()
  4. # 调用方法,标识没有远程机器的公钥,允许访问
  5. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  6. # 连接远程机器 地址端口用户名密码
  7. ssh.connect( "xx.xx.xx.xx", 22, "root", "xxxxx")
  8. # 执行命令
  9. #ssh.exec_command('echo $?')
  10. stdin,stdout,stderr = ssh.exec_command( 'date +"%Y%m%d"')
  11. print(stdout.read().decode( "utf-8"))
  12. ssh.close()
  • 3 连接MySQL等数据库

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

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


   
  1. from tkinter import *
  2. import tkinter.font as tf
  3. def btn_click():
  4. text.insert(INSERT,( "输入错误,请确定输入值!\n"))
  5. def specialType():
  6. # 调整字体高亮
  7. ft = tf.Font(family= '微软雅黑',size= 10)
  8. text.tag_config( 'tag',foreground = 'blue',background= 'pink',font = ft)
  9. text.insert(INSERT, "您选择的是特情码字典,查询结果如下:\n", 'tag')
  10. # enter调用
  11. def btn_click_enter(self):
  12. btn_click()
  13. # 清空消息
  14. def cleartext():
  15. text.delete( '0.0', END)
  16. # 创建窗口对象的背景色
  17. root = Tk()
  18. root.title( '便捷式一键查询服务系统')
  19. root.geometry( '960x700')
  20. # Frame为布局函数
  21. main_frame = Frame(root)
  22. text_frame = Frame(main_frame)
  23. station_frame = Frame(main_frame)
  24. botton_frame = Frame(station_frame)
  25. # 建立列表
  26. l1 = Label(station_frame,text= '输入门架,站码,IP,互通,厂商或相关拼音')
  27. #l2 = Label(station_frame,text='')
  28. ipText=Entry(station_frame)
  29. # 字体显示
  30. # ft = tkFont.Font(family='Fixdsys', size=10, weight=tkFont.BOLD)
  31. # pack是加载到窗口
  32. l1.pack(side= 'left')
  33. ipText.pack(side= 'left')
  34. ipText[ 'width']= 24
  35. #l2.pack(side='left')
  36. '''
  37. 两个函数的意义是既能enter运行,又可以点击运行,方便操作,扩大使用
  38. bind绑定enter键
  39. 注意里面是return 而不是enter
  40. '''
  41. b = Button(station_frame,text= '查询',command=btn_click)
  42. b[ 'width']= 4
  43. b[ 'height']= 1
  44. b.pack(side= 'left')
  45. ipText.bind( "<Return>", btn_click_enter)
  46. # 消息输入界面
  47. text = Text(text_frame,width = 130, height= 39)
  48. text.pack()
  49. main_frame.pack()
  50. c = Button(text= '清空',command=cleartext)
  51. c[ 'width']= 4
  52. c[ 'height']= 1
  53. c.pack(side= 'left')
  54. # 第二个函数
  55. d = Button(text= '导出excel',command=excelExport)
  56. d[ 'width']= 8
  57. d[ 'height']= 1
  58. d.pack(side= 'top')
  59. # 输入框的位置
  60. station_frame.pack(side= 'top',pady= '10')
  61. text_frame.pack()
  62. # 进入消息循环
  63. root.mainloop()
  • 5 常用IO读写

  • 5.1 文本写入

   
  1. # 这个与简单的io open close的区别是后者是在内存里边写边存的,必须要close文件,否则可能容易造成数据丢失
  2. # r 是只读,文件不存在报错,r+是读写
  3. # w 是只写,覆盖,文件不存在会创建,w+是读写
  4. # a 是只写,追加,文件不存在会创建,a+是读写
  5. import codecs
  6. with codecs.open(file, 'a+',encoding= 'utf-8') as f:
  7. f.write(df.ip[i]+ ','+station+ ','+df.big[i]+ ','+df.small[i]+ ','+ '正常联网'+ '\n')
  • 5.2 读取字典到文件

   
  1. import codecs
  2. import json
  3. file1 = "D:\\result\\result%s.csv" % date1
  4. # r是读,w是覆盖,a是追加,后面跟个+是文件不存在就创建,如果还包括路径,则需要os包来创建
  5. # 读取字典
  6. file = open(file1, 'r')
  7. '''
  8. import os
  9. dirs = '/Users/joseph/work/python/'
  10. if not os.path.exists(dirs):
  11. os.makedirs(dirs)
  12. '''
  13. js = file.read()
  14. dict_num = json.loads(js)
  15. # 字典写入文件
  16. with codecs.open(file_i, 'w',encoding= 'utf-8') as f:
  17. json.dump(dict_num,f)
  • 6 SQL查询结果excel导出


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


   
  1. import os as os
  2. import codecs
  3. class EasyStation:
  4. # 读取站名,类型强转
  5. num1 = int(input( "请输入数字站码: "))
  6. dict1 = { 1111:[ 'test1', 'xx.xx.xx.xx'], 1113:[ 'test2', 'xx.xx.xx.xx']}
  7. # 对错误站名做异常处理
  8. try:
  9. servername = dict1[num1][ 0]
  10. dbip = dict1[num1][ 1]
  11. file1 = "foo.txt"
  12. if os.path.exists(file1):
  13. print ( "file have been existed , del firstly")
  14. os.remove(file1)
  15. else:
  16. with codecs.open(file1, 'w',encoding= 'utf-8') as f:
  17. f.write( u"[serverinfo]\nserverNum=1\nnum1=" + str(num1) + "\n" + "[")
  18. # 启动
  19. def open_app(app_dir):
  20. os.startfile(app_dir)
  21. if __name__ == "__main__":
  22. app_dir = r'D:\Program Files (x86)\Youdao\YoudaoNote\YoudaoNote.exe'
  23. open_app(app_dir)
  24. except KeyError:
  25. print ( "Error:未找到该站名,请查证")
  • 8 ping网络


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


   
  1. import numpy as np
  2. import matplotlib as mpl
  3. import matplotlib.pyplot as plt
  4. from pylab import *
  5. mpl.rcParams[ 'font.sans-serif'] = [ 'SimHei']
  6. mpl.rcParams[ 'axes.unicode_minus'] = False
  7. # 导入数据
  8. sj=[ '00', '01', '02', '03', '04', '05', '06', '18', '19', '20', '21', '22', '23']
  9. #sj = filter(lambda x:x%200 == 0, zl)
  10. 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]
  11. 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]
  12. #开始画图
  13. plt.title( '醒目工程安装前后对比图')
  14. plt.plot(sj, sp1, color= 'red', label= '安装前1车道车速')
  15. plt.plot(sj, sp2, color= 'green', label= '安装后1车道车速')
  16. plt.legend() # 显示图例
  17. plt.xlabel( '小时')
  18. plt.ylabel( '车速')
  19. #plt.savefig("temp1.jpg")
  20. plt.show()
  • 10 匿名函数&不定量元素输入


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

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

  • 12 PyQt多个日历时间模块加载与选择时间获取


   
  1. import sys
  2. from PyQt5.QtCore import QDate,QDateTime,QTime
  3. from PyQt5.QtWidgets import *
  4. from PyQt5.QtGui import *
  5. import time
  6. class DateTimeEditDemo(QWidget):
  7. def __init__(self):
  8. super(DateTimeEditDemo, self).__init__()
  9. self.initUI()
  10. def initUI(self):
  11. #设置标题与初始大小
  12. self.setWindowTitle( '镇海危化品车查询')
  13. self.resize( 500, 380)
  14. #垂直布局/水平布局 QVBoxLayout/QHBoxLayout
  15. layout=QVBoxLayout()
  16. self.setLayout(layout)
  17. #创建第一个日期时间空间,并把当前日期时间赋值,并修改显示格式
  18. self.label1 = QLabel( '开始时间')
  19. self.dateEdit1=QDateTimeEdit(QDateTime.currentDateTime(),self)
  20. self.dateEdit1.setDisplayFormat( 'yyyy-MM-dd HH:mm:ss')
  21. #设置第一个日期最大值与最小值,在当前日期的基础上,后一年与前一年
  22. self.dateEdit1.setMinimumDate(QDate.currentDate().addDays( -365))
  23. self.dateEdit1.setMaximumDate(QDate.currentDate().addDays( 365))
  24. #设置第一个日历控件允许弹出
  25. self.dateEdit1.setCalendarPopup( True)
  26. self.label2 = QLabel( '结束时间')
  27. #创建第二个日期时间空间,并把当前日期时间赋值,。并修改显示格式
  28. self.dateEdit2=QDateTimeEdit(QDateTime.currentDateTime(),self)
  29. self.dateEdit2.setDisplayFormat( 'yyyy-MM-dd HH:mm:ss')
  30. #设置第二个日期最大值与最小值,在当前日期的基础上,后一年与前一年
  31. self.dateEdit2.setMinimumDate(QDate.currentDate().addDays( -365))
  32. self.dateEdit2.setMaximumDate(QDate.currentDate().addDays( 365))
  33. #设置第二个日历控件允许弹出
  34. self.dateEdit2.setCalendarPopup( True)
  35. #创建按钮并绑定一个自定义槽函数
  36. self.btn=QPushButton( '点击查询')
  37. self.btn.clicked.connect(self.onButtonClick)
  38. #创建文本框用于显示想要输出的内容
  39. self.textEdit = QTextEdit()
  40. #布局控件的加载与设置,可加载多个控件
  41. layout.addWidget(self.label1)
  42. layout.addWidget(self.dateEdit1)
  43. layout.addWidget(self.label2)
  44. layout.addWidget(self.dateEdit2)
  45. layout.addWidget(self.btn)
  46. layout.addWidget(self.textEdit)
  47. def onButtonClick(self):
  48. #dateTime是QDateTimeEdit的一个方法,返回QDateTime时间格式
  49. #需要再用toPyDateTime转变回python的时间格式
  50. dateTime1=str(self.dateEdit1.dateTime().toPyDateTime())[ 0: 19]
  51. dateTime2=str(self.dateEdit2.dateTime().toPyDateTime())[ 0: 19]
  52. #python时间格式转换
  53. n_time11 = time.strptime(dateTime1, "%Y-%m-%d %H:%M:%S")
  54. n_time22 = time.strptime(dateTime2, "%Y-%m-%d %H:%M:%S")
  55. n_time1 = int(time.strftime( '%Y%m%d%H%M%S',n_time11))
  56. n_time2 = int(time.strftime( '%Y%m%d%H%M%S',n_time22))
  57. self.textEdit.setText( "This is pyqt's test!")
  58. #if __name__ == '__main__'的作用是为了防止其他脚本只是调用该类时才开始加载,优化内存使用
  59. if __name__ == '__main__':
  60. #调用
  61. app=QApplication(sys.argv)
  62. demo=DateTimeEditDemo()
  63. demo.show()
  64. sys.exit(app.exec_())
  • 13 for循环多个变量(zip)


   
  1. for i,j,z in zip([ 1, 2, 3, 4],[ 'test1', 'test2', 'test3', 'test4'],[ 11, 22, 33, 44]):
  2. print(i,j,z)
  • 14 爬虫,王者荣耀皮肤爬取


   
  1. import os
  2. import requests
  3. url = 'https://pvp.qq.com/web201605/js/herolist.json'
  4. herolist = requests.get(url) # 获取英雄列表json文件
  5. herolist_json = herolist.json() # 转化为json格式
  6. hero_name = list(map( lambda x: x[ 'cname'], herolist.json())) # 提取英雄的名字
  7. hero_number = list(map( lambda x: x[ 'ename'], herolist.json())) # 提取英雄的编号
  8. # 下载图片
  9. def downloadPic():
  10. i = 0
  11. for j in hero_number:
  12. # 创建文件夹
  13. os.mkdir( "C:\\Users\\dtboy\\Desktop\\downWz\\" + hero_name[i])
  14. # 进入创建好的文件夹
  15. os.chdir( "C:\\Users\\dtboy\\Desktop\\downWz\\" + hero_name[i])
  16. i += 1
  17. for k in range( 10):
  18. # 拼接url
  19. onehero_link = 'http://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/' + str(j) + '/' + str(j) + '-bigskin-' + str(k) + '.jpg'
  20. im = requests.get(onehero_link) # 请求url
  21. if im.status_code == 200:
  22. open(str(k) + '.jpg', 'wb').write(im.content) # 写入文件
  23. downloadPic()
  • 15 python依据文件内容改文件名


   
  1. import os
  2. import pandas as pd
  3. import time
  4. # 获取桌面上的etc文件夹
  5. path = os.path.join(os.path.expanduser( '~'), "Desktop") + "\\etc"
  6. dirs = os.listdir(path)
  7. #遍历文件改名
  8. for file in dirs:
  9. file_ = os.path.join(path,file)
  10. df = pd.read_excel(file_,header= None)
  11. x1 = str(df.iloc[ 0, 0]).replace( '明细', '')
  12. date1 = int(time.strftime( '%Y%m%d',time.strptime(x1[ -20, -10], '%Y-%m-%d')))
  13. nname = file.split( '-')[ 0] + '_' + str(date1) + '.xls'
  14. os.rename(path+ "\\"+file,path+ "\\"_nname)
  15. print( 'succ!')

本demo依据实际场景改名,详情点击博客这是一个小链接查看背景与脚本介绍 

  • 16 时间的转换与计算

单独一章,见链接:https://blog.csdn.net/mochou111/article/details/107783146 


转载:https://blog.csdn.net/mochou111/article/details/106193649
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场