脚本写的好,下班下得早!程序员的日常工作除了编写程序代码,还不可避免地需要处理相关的测试和验证工作。

例如,访问某个网站一直不通,需要确定此地址是否可访问,服务器返回什么,进而确定问题在于什么。完成这个任务,如果一味希望采用编译型语言来编写这样的代码,实践中的时间和精力是不够的,这个时候就需要发挥脚本的神奇作用!

好不夸张的说,能否写出高效实用的脚本代码,直接影响着一个程序员的幸福生活[下班时间]。下面整理 8 个实用的 Python 脚本,需要的时候改改直接用,建议收藏!

1.解决 linux 下 unzip 乱码的问题。

import os
import sys
import zipfile
import argparses = '\x1b[%d;%dm%s\x1b[0m'       def unzip(path):file = zipfile.ZipFile(path,"r")if args.secret:file.setpassword(args.secret)for name in file.namelist():try:utf8name=name.decode('gbk')pathname = os.path.dirname(utf8name)except:utf8name=namepathname = os.path.dirname(utf8name)#print s % (1, 92, '  >> extracting:'), utf8name#pathname = os.path.dirname(utf8name)if not os.path.exists(pathname) and pathname != "":os.makedirs(pathname)data = file.read(name)if not os.path.exists(utf8name):try:fo = open(utf8name, "w")fo.write(data)fo.closeexcept:passfile.close()def main(argv):####################################################### for argparsep = argparse.ArgumentParser(description='解决unzip乱码')p.add_argument('xxx', type=str, nargs='*', \help='命令对象.')p.add_argument('-s', '--secret', action='store', \default=None, help='密码')global argsargs = p.parse_args(argv[1:])xxx = args.xxxfor path in xxx:if path.endswith('.zip'):if os.path.exists(path):print s % (1, 97, '  ++ unzip:'), pathunzip(path)else:print s % (1, 91, '  !! file doesn\'t exist.'), pathelse:print s % (1, 91, '  !! file isn\'t a zip file.'), pathif __name__ == '__main__':argv = sys.argvmain(argv)

2.统计当前根目录代码行数。

# coding=utf-8
import os
import time
# 设定根目录
basedir = './'
filelists = []
# 指定想要统计的文件类型
whitelist = ['cpp', 'h']
#遍历文件, 递归遍历文件夹中的所有
def getFile(basedir):global filelistsfor parent,dirnames,filenames in os.walk(basedir):for filename in filenames:ext = filename.split('.')[-1]#只统计指定的文件类型,略过一些log和cache文件if ext in whitelist:filelists.append(os.path.join(parent,filename))
#统计一个的行数
def countLine(fname):count = 0# 把文件做二进制看待,read.for file_line in open(fname, 'rb').readlines():if file_line != '' and file_line != '\n': #过滤掉空行count += 1print (fname + '----' , count)return count
if __name__ == '__main__' :startTime = time.clock()getFile(basedir)totalline = 0for filelist in filelists:totalline = totalline + countLine(filelist)print ('total lines:',totalline)print ('Done! Cost Time: %0.2f second' % (time.clock() - startTime))

3.扫描当前目录和所有子目录并显示大小。

import os
import sys
try:directory = sys.argv[1]
except IndexError:sys.exit("Must provide an argument.")dir_size = 0
fsizedicr = {'Bytes': 1,'Kilobytes': float(1) / 1024,'Megabytes': float(1) / (1024 * 1024),'Gigabytes': float(1) / (1024 * 1024 * 1024)}
for (path, dirs, files) in os.walk(directory):      for file in files:                              filename = os.path.join(path, file)dir_size += os.path.getsize(filename)       fsizeList = [str(round(fsizedicr[key] * dir_size, 2)) + " " + key for key in fsizedicr] if dir_size == 0: print ("File Empty")
else:for units in sorted(fsizeList)[::-1]: print ("Folder Size: " + units)

4.将源目录240天以上的所有文件移动到目标目录。

import shutil
import sys
import time
import os
import argparseusage = 'python move_files_over_x_days.py -src [SRC] -dst [DST] -days [DAYS]'
description = 'Move files from src to dst if they are older than a certain number of days.  Default is 240 days'args_parser = argparse.ArgumentParser(usage=usage, description=description)
args_parser.add_argument('-src', '--src', type=str, nargs='?', default='.', help='(OPTIONAL) Directory where files will be moved from. Defaults to current directory')
args_parser.add_argument('-dst', '--dst', type=str, nargs='?', required=True, help='(REQUIRED) Directory where files will be moved to.')
args_parser.add_argument('-days', '--days', type=int, nargs='?', default=240, help='(OPTIONAL) Days value specifies the minimum age of files to be moved. Default is 240.')
args = args_parser.parse_args()if args.days < 0:args.days = 0src = args.src  # 设置源目录
dst = args.dst  # 设置目标目录
days = args.days # 设置天数
now = time.time()  # 获得当前时间if not os.path.exists(dst):os.mkdir(dst)for f in os.listdir(src):  # 遍历源目录所有文件if os.stat(f).st_mtime < now - days * 86400:  # 判断是否超过240天if os.path.isfile(f):  # 检查是否是文件shutil.move(f, dst)  # 移动文件

5.扫描脚本目录,并给出不同类型脚本的计数。

import os
import shutil
from time import strftime                                               logsdir="c:\logs\puttylogs"
zipdir="c:\logs\puttylogs\zipped_logs"
zip_program="zip.exe"                                                for files in os.listdir(logsdir):                                       if files.endswith(".log"):                                        files1=files+"."+strftime("%Y-%m-%d")+".zip"      os.chdir(logsdir)                                               os.system(zip_program + " " +  files1 +" "+ files)  shutil.move(files1, zipdir)                                  os.remove(files)

6.下载Leetcode的算法题。

import sys
import re
import os
import argparse
import requests
from lxml import html as lxml_htmltry:import html
except ImportError:import HTMLParserhtml = HTMLParser.HTMLParser()try:import cPickle as pk
except ImportError:import pickle as pkclass LeetcodeProblems(object):def get_problems_info(self):leetcode_url = 'https://leetcode.com/problemset/algorithms'res = requests.get(leetcode_url)if not res.ok:print('request error')sys.exit()cm = res.textcmt = cm.split('tbody>')[-2]indexs = re.findall(r'<td>(\d+)</td>', cmt)problem_urls = ['https://leetcode.com' + url \for url in re.findall(r'<a href="(/problems/.+?)"', cmt)]levels = re.findall(r"<td value='\d*'>(.+?)</td>", cmt)tinfos = zip(indexs, levels, problem_urls)assert (len(indexs) == len(problem_urls) == len(levels))infos = []for info in tinfos:res = requests.get(info[-1])if not res.ok:print('request error')sys.exit()tree = lxml_html.fromstring(res.text)title = tree.xpath('//meta[@property="og:title"]/@content')[0]description = tree.xpath('//meta[@property="description"]/@content')if not description:description = tree.xpath('//meta[@property="og:description"]/@content')[0]else:description = description[0]description = html.unescape(description.strip())tags = tree.xpath('//div[@id="tags"]/following::a[@class="btn btn-xs btn-primary"]/text()')infos.append({'title': title,'level': info[1],'index': int(info[0]),'description': description,'tags': tags})with open('leecode_problems.pk', 'wb') as g:pk.dump(infos, g)return infosdef to_text(self, pm_infos):if self.args.index:key = 'index'elif self.args.title:key = 'title'elif self.args.tag:key = 'tags'elif self.args.level:key = 'level'else:key = 'index'infos = sorted(pm_infos, key=lambda i: i[key])text_template = '## {index} - {title}\n' \'~{level}~  {tags}\n' \'{description}\n' + '\n' * self.args.linetext = ''for info in infos:if self.args.rm_blank:info['description'] = re.sub(r'[\n\r]+', r'\n', info['description'])text += text_template.format(**info)with open('leecode problems.txt', 'w') as g:g.write(text)def run(self):if os.path.exists('leecode_problems.pk') and not self.args.redownload:with open('leecode_problems.pk', 'rb') as f:pm_infos = pk.load(f)else:pm_infos = self.get_problems_info()print('find %s problems.' % len(pm_infos))self.to_text(pm_infos)def handle_args(argv):p = argparse.ArgumentParser(description='extract all leecode problems to location')p.add_argument('--index', action='store_true', help='sort by index')p.add_argument('--level', action='store_true', help='sort by level')p.add_argument('--tag', action='store_true', help='sort by tag')p.add_argument('--title', action='store_true', help='sort by title')p.add_argument('--rm_blank', action='store_true', help='remove blank')p.add_argument('--line', action='store', type=int, default=10, help='blank of two problems')p.add_argument('-r', '--redownload', action='store_true', help='redownload data')args = p.parse_args(argv[1:])return argsdef main(argv):args = handle_args(argv)x = LeetcodeProblems()x.args = argsx.run()if __name__ == '__main__':argv = sys.argvmain(argv)

7.将 Markdown 转换为 HTML。

import sys
import osfrom bs4 import BeautifulSoup
import markdownclass MarkdownToHtml:headTag = '<head><meta charset="utf-8" /></head>'def __init__(self,cssFilePath = None):if cssFilePath != None:self.genStyle(cssFilePath)def genStyle(self,cssFilePath):with open(cssFilePath,'r') as f:cssString = f.read()self.headTag = self.headTag[:-7] + '<style type="text/css">{}</style>'.format(cssString) + self.headTag[-7:]def markdownToHtml(self, sourceFilePath, destinationDirectory = None, outputFileName = None):if not destinationDirectory:# 未定义输出目录则将源文件目录(注意要转换为绝对路径)作为输出目录destinationDirectory = os.path.dirname(os.path.abspath(sourceFilePath))if not outputFileName:# 未定义输出文件名则沿用输入文件名outputFileName = os.path.splitext(os.path.basename(sourceFilePath))[0] + '.html'if destinationDirectory[-1] != '/':destinationDirectory += '/'with open(sourceFilePath,'r', encoding='utf8') as f:markdownText = f.read()# 编译出原始 HTML 文本rawHtml = self.headTag + markdown.markdown(markdownText,output_format='html5')# 格式化 HTML 文本为可读性更强的格式beautifyHtml = BeautifulSoup(rawHtml,'html5lib').prettify()with open(destinationDirectory + outputFileName, 'w', encoding='utf8') as f:f.write(beautifyHtml)if __name__ == "__main__":mth = MarkdownToHtml()# 做一个命令行参数列表的浅拷贝,不包含脚本文件名argv = sys.argv[1:]# 目前列表 argv 可能包含源文件路径之外的元素(即选项信息)# 程序最后遍历列表 argv 进行编译 markdown 时,列表中的元素必须全部是源文件路径outputDirectory = Noneif '-s' in argv:cssArgIndex = argv.index('-s') +1cssFilePath = argv[cssArgIndex]# 检测样式表文件路径是否有效if not os.path.isfile(cssFilePath):print('Invalid Path: '+cssFilePath)sys.exit()mth.genStyle(cssFilePath)# pop 顺序不能随意变化argv.pop(cssArgIndex)argv.pop(cssArgIndex-1)if '-o' in argv:dirArgIndex = argv.index('-o') +1outputDirectory = argv[dirArgIndex]# 检测输出目录是否有效if not os.path.isdir(outputDirectory):print('Invalid Directory: ' + outputDirectory)sys.exit()# pop 顺序不能随意变化argv.pop(dirArgIndex)argv.pop(dirArgIndex-1)# 至此,列表 argv 中的元素均是源文件路径# 遍历所有源文件路径for filePath in argv:# 判断文件路径是否有效if os.path.isfile(filePath):mth.markdownToHtml(filePath, outputDirectory)else:print('Invalid Path: ' + filePath)

8.文本文件编码检测与转换。

import sys
import os
import argparse
from chardet.universaldetector import UniversalDetectorparser = argparse.ArgumentParser(description = '文本文件编码检测与转换')
parser.add_argument('filePaths', nargs = '+',help = '检测或转换的文件路径')
parser.add_argument('-e', '--encoding', nargs = '?', const = 'UTF-8',help = '''
目标编码。支持的编码有:
ASCII, (Default) UTF-8 (with or without a BOM), UTF-16 (with a BOM),
UTF-32 (with a BOM), Big5, GB2312/GB18030, EUC-TW, HZ-GB-2312, ISO-2022-CN, EUC-JP, SHIFT_JIS, ISO-2022-JP,
ISO-2022-KR, KOI8-R, MacCyrillic, IBM855, IBM866, ISO-8859-5, windows-1251, ISO-8859-2, windows-1250, EUC-KR,
ISO-8859-5, windows-1251, ISO-8859-1, windows-1252, ISO-8859-7, windows-1253, ISO-8859-8, windows-1255, TIS-620
''')
parser.add_argument('-o', '--output',help = '输出目录')
# 解析参数,得到一个 Namespace 对象
args = parser.parse_args()
# 输出目录不为空即视为开启转换, 若未指定转换编码,则默认为 UTF-8
if args.output != None:if not args.encoding:# 默认使用编码 UTF-8args.encoding = 'UTF-8'# 检测用户提供的输出目录是否有效if not os.path.isdir(args.output):print('Invalid Directory: ' + args.output)sys.exit()else:if args.output[-1] != '/':args.output += '/'
# 实例化一个通用检测器
detector = UniversalDetector()
print()
print('Encoding (Confidence)',':','File path')
for filePath in args.filePaths:# 检测文件路径是否有效,无效则跳过if not os.path.isfile(filePath):print('Invalid Path: ' + filePath)continue# 重置检测器detector.reset()# 以二进制模式读取文件for each in open(filePath, 'rb'):# 检测器读取数据detector.feed(each)# 若检测完成则跳出循环if detector.done:break# 关闭检测器detector.close()# 读取结果charEncoding = detector.result['encoding']confidence = detector.result['confidence']# 打印信息if charEncoding is None:charEncoding = 'Unknown'confidence = 0.99print('{} {:>12} : {}'.format(charEncoding.rjust(8),'('+str(confidence*100)+'%)', filePath))if args.encoding and charEncoding != 'Unknown' and confidence > 0.6:# 若未设置输出目录则覆盖源文件outputPath = args.output + os.path.basename(filePath) if args.output else filePathwith open(filePath, 'r', encoding = charEncoding, errors = 'replace') as f:temp = f.read()with open(outputPath, 'w', encoding = args.encoding, errors = 'replace') as f:f.write(temp)

最后两个脚本内容选至实验楼的课程《使用 Python3 编写系列实用脚本》,课程对这两个脚本有详细的实现过程讲解,感兴趣的同学可以直接前往实验楼进行学习!

知乎专栏同步:https://zhuanlan.zhihu.com/p/85728888

8 个 Python 实用脚本,赶紧收藏备用!相关推荐

  1. Emscripten 单词_分享15个英语单词记忆方法,简单实用,赶紧收藏吧!

    分享15个英语单词记忆方法,简单实用,赶紧收藏吧! 单词是学习英语的基石,英语程度的好坏,单词是最重要的衡量标准.单词的构成方式其实很简单,就是26个字母的排列组合. 那有什么方法能够让我们更好地把单 ...

  2. Python实用脚本实践

    Python实用脚本实践 一.文件相关 查找文件 import os path = 'xxx' files = os.listdir(path)for f in files:if f.endswith ...

  3. python实用脚本 知乎_停课不停学|38 个免费 Python 项目合集,从小白到老司机!...

    1665 年,牛顿在剑桥三一学院就读期间,伦敦发生了著名的鼠疫.这场鼠疫几乎摧毁了整个伦敦城,无论是下层人民还是王室贵族都难逃魔掌,几乎五分之一的伦敦人都在这场鼠疫中丧生. 牛顿被迫回家进行自我隔离, ...

  4. python parser count_8个超实用的Python脚本,收藏备用

    脚本写的好,下班下得早!程序员的日常工作除了编写程序代码,还不可避免地需要处理相关的测试和验证工作. 例如,访问某个网站一直不通,需要确定此地址是否可访问,服务器返回什么,进而确定问题在于什么.完成这 ...

  5. 8个Python实用脚本

    例如,访问某个网站一直不通,需要确定此地址是否可访问,服务器返回什么,进而确定问题在于什么.完成这个任务,如果一味希望采用编译型语言来编写这样的代码,实践中的时间和精力是不够的,这个时候就需要发挥脚本 ...

  6. python parser count_8 个 Python 实用脚本,早掌握早下班!

    脚本写的好,下班下得早!程序员的日常工作除了编写程序代码,还不可避免地需要处理相关的测试和验证工作. 例如,访问某个网站一直不通,需要确定此地址是否可访问,服务器返回什么,进而确定问题在于什么.完成这 ...

  7. 什么?用Python实用脚本也能实现快速卡通画人物头像,这不就是妥妥的QQ秀嘛。

    前言 今天我们就利用Python脚本实现天气查询应用吧.直接开整~ 思路分析 从大量照片/卡通数据中习得照片到卡通画的映射. 开发工具 python版本: 3.6 相关模块: pytorch 1.4 ...

  8. python实用脚本-获取软件md5值

    我们下载软件过程中,为了确保下载的软件没有被修改过,可以通过python脚本校验md5值,若与官方给出的md5不一致,则表示该软件被修改过,不安全,若一致,则软件是可信的.举例如下,下载python软 ...

  9. Python实用脚本/算法集合, 附源代码下载

    学习编程.学习Python最好的方式就是练习,哪怕是新手,只要不断地敲代码输出,肯定会有神效. Python的练手项目很多,特别是Github上,建议不管新手.老司机都去看看. 这里推荐给大家两个Gi ...

最新文章

  1. 继往开来:Google I/O 21 Android Gradle Plugin 更新总结
  2. 6 关于数据仓库维度数据处理的方法探究系列——缓慢变化维处理——记录最新记录及上一次历史...
  3. hdu 1116 Play on Words
  4. 腾讯、阿里到底有多缺这类程序员?
  5. spring基础系列--JavaConfig配置
  6. 删除已有的 HTML 元素
  7. 盘点八个程序员必备的代码编辑器
  8. 饿了吗商品列表_仅仅一字之差,饿了么起诉饿了吗
  9. 使用jquery.form.js实现form表单无刷新提交简单示例
  10. Eclipse Egit 安装
  11. WinRunner的工作流程
  12. 把rmvb格式转化为avi格式
  13. 修改dns服务器转发器,域服务器dns设置转发器
  14. PDF打开后出现中文乱码情况
  15. 深度学习#tensorflow进阶
  16. 一级计算机windows考试试题,2001年4月全国计算机等级考试一级笔试试题Windows
  17. 免费又好用的Windows任务栏透明化工具——Translucent TB
  18. i9 10900K比9900K性能提升了多少?i9-10900K和i9-9900K区别对比评测 更多详情咨询世通兰陵王
  19. 异常:git did not exit cleanly (exit code 128)
  20. Pycharm专业版下载及安装,使用python解释器运行(官网)

热门文章

  1. django【orm操作】
  2. 【云计算】使用privilege权限对Docker内核参数进行定制
  3. AppDelegate 处理iOS应用的生命周期事件
  4. 检测客户pc电脑端VC++环境并安装
  5. python字符串应用
  6. MySQL安装教程图解
  7. XML 序列化与反序列化
  8. Linux 安装Redis全过程日志
  9. Java 读取 .properties 配置文件的几种方式
  10. 25、【华为HCIE-Storage】--Hyper Snapshot(文件业务)