8个Python实用脚本,赶紧收藏

2023-11-17

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

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

 

这里还要注意:不管你是为了Python就业还是兴趣爱好,记住:项目开发经验永远是核心,如果你没有2020最新python入门到高级实战视频教程,可以去小编的Python交流.裙 :七衣衣九七七巴而五(数字的谐音)转换下可以找到了,里面很多新python教程项目,还可以跟老司机交流讨教!

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

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

import os
import sys
import zipfile
import argparse

s = '\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=name
            pathname = 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.close
            except:
                pass
    file.close()

def main(argv):
    ######################################################
    # for argparse
    p = argparse.ArgumentParser(description='解决unzip乱码')
    p.add_argument('xxx', type=str, nargs='*', \
        help='命令对象.')
    p.add_argument('-s', '--secret', action='store', \
        default=None, help='密码')
    global args
    args = p.parse_args(argv[1:])
    xxx = args.xxx

    for path in xxx:
        if path.endswith('.zip'):
            if os.path.exists(path):
                print s % (1, 97, '  ++ unzip:'), path
                unzip(path)
            else:
                print s % (1, 91, '  !! file doesn\'t exist.'), path
        else:
            print s % (1, 91, '  !! file isn\'t a zip file.'), path

if __name__ == '__main__':
    argv = sys.argv
    main(argv)
复制代码

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

# coding=utf-8
import os
import time
# 设定根目录
basedir = './'
filelists = []
# 指定想要统计的文件类型
whitelist = ['cpp', 'h']
#遍历文件, 递归遍历文件夹中的所有
def getFile(basedir):
    global filelists
    for 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 += 1
    print (fname + '----' , count)
    return count
if __name__ == '__main__' :
    startTime = time.clock()
    getFile(basedir)
    totalline = 0
    for 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 argparse

usage = '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 = 0

src = 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_html

try:
    import html
except ImportError:
    import HTMLParser
    html = HTMLParser.HTMLParser()

try:
    import cPickle as pk
except ImportError:
    import pickle as pk

class 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.text
        cmt = 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 infos

    def 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.line
        text = ''
        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 args

def main(argv):
    args = handle_args(argv)
    x = LeetcodeProblems()
    x.args = args
    x.run()

if __name__ == '__main__':
    argv = sys.argv
    main(argv)
复制代码

7.将 Markdown 转换为 HTML。

import sys
import os

from bs4 import BeautifulSoup
import markdown

class 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 = None
    if '-s' in argv:
        cssArgIndex = argv.index('-s') +1
        cssFilePath = 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') +1
        outputDirectory = 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 UniversalDetector

parser = 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-8
        args.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.99
    print('{} {:>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 filePath
        with 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 编写系列实用脚本》课程对这两个脚本有详细的实现过程讲解,最后注意:不管你是为了Python就业还是兴趣爱好,记住:项目开发经验永远是核心,如果你没有2020最新python入门到高级实战视频教程,可以去小编的Python交流.裙 :七衣衣九七七巴而五(数字的谐音)转换下可以找到了,里面很多新python教程项目,还可以跟老司机交流讨教!
本文的文字及图片来源于网络加上自己的想法,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

8个Python实用脚本,赶紧收藏 的相关文章

随机推荐

  • gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting

    gzip stdin not in gzip format tar Child returned status 1 tar Error is not recoverable exiting now 可能是下载链接不是资源链接 而是页面
  • Android 构建配置文件(config.gradle)

    1 新建config gradle 在自己的项目根目录下一个文件夹下创建一个config gradle文件名的文件 和settings gradble同目录 把自己需要用到的库跟版本号写在dependencies 标签括号内 ext and
  • springboot前后端分离之node.js环境搭建

    参考自链接 https www cnblogs com zhouyu2017 p 6485265 html Node js安装及环境配置之Windows篇 一 安装环境 1 本机系统 Windows 10 Pro 64位 2 Node js
  • Nacos 单机模式部署(Windows系统)

    Nacos 下载地址 Nacos 是阿里巴巴推出来的一个项目 这是一个更易于构建云原生应用的动态服务发现 配置管理和服务管理平台 Nacos 致力于帮助您发现 配置和管理微服务 Nacos 提供了一组简单易用的特性集 帮助您快速实现动态服务
  • 区块链学习5:智能合约Smart contract原理及发展历程科普知识

    前往老猿Python博文目录 一 智能合约的定义 通俗来说 智能合约就是一种在计算机系统上 当一定条件满足的情况下可被自动执行的合约 智能合约体现为一段代码及其运行环境 例如银行信用卡的自动还款就是一种典型的智能合约 我们来看看智能合约概念
  • 三维形体投影面积

    三维形体投影面积 在 n x n 的网格 grid 中 我们放置了一些与 x y z 三轴对齐的 1 x 1 x 1 立方体 每个值 v grid i j 表示 v 个正方体叠放在单元格 i j 上 现在 我们查看这些立方体在 xy yz
  • Java格式化字符串

    String类的静态format 方法用于创建格式化的字符串 format 方法有两种重载形式 1 public static String format String format Object args 该方法使用指定的格式字符串和参数
  • Java无向图链表、邻接表实现以及深度优先遍历广度优先遍历

    概述 图的存储形式中链表是通过数组加LinkedList 不一定是LinkedList 可以自己写链 也可以选择其他的集合数据结构 邻接表采用的是二维数组的结构 链表存储形式的相关实现 数据存储结构与基础操作 初始化数据存储结构 priva
  • mysql5.7小版本升级-windows

    mysql5 7小版本升级 windows 应用场景 mysql 5 7 20升级到当前最新的5 7 31 Windows环境 官网下载链接 https dev mysql com downloads mysql 5 7 html 注意 操
  • 区间预测

    区间预测 MATLAB实现GARCH分位数时间序列预测 目录 区间预测 MATLAB实现GARCH分位数时间序列预测 效果一览 基本介绍 模型描述 程序设计 研究总结 参考文献 效果一览 基本介绍 GARCH代表广义自回归条件异方差 它是一
  • 2015~2019年教育大数据会议期刊汇总及论文总结(不再更新)

    以下论文大部分与个性化导学相关 1 数据挖掘会议 AAAI AAAI 17 Question dif culty prediction for reading problems in standard tests AAAI 18 Medic
  • ftp服务器密码为空,ftp服务器无密码设置密码

    ftp服务器无密码设置密码 内容精选 换一换 华为云帮助中心 为用户提供产品简介 价格说明 购买指南 用户指南 API参考 最佳实践 常见问题 视频帮助等技术文档 帮助您快速上手使用华为云服务 如果在创建弹性云服务器时未设置密码 或密码丢失
  • 可以自定义公式的计算器_超多的计算器 总有一个用得上

    本期为大家分享几款计算器 这几款计算器足以满足你所有需求 功能强大 你值得拥有 01 Symbolab Practice 你的私人数学导师 以步骤展示任何数学问题解决步骤 数学计算Symbolab计算器将能为你解决 1 代数 等式 不等式
  • 单链表(数组模拟:静态链表)

    单链表 实现一个单链表 链表初始为空 支持三种操作 向链表头插入一个数 删除第 kk 个插入的数后面的数 在第 kk 个插入的数后插入一个数 现在要对该链表进行 MM 次操作 进行完所有操作后 从头到尾输出整个链表 注意 题目中第 kk 个
  • MySQL 临时表与内存表的区别

    文章目录 1 临时表 2 内存表 3 区别 4 小结 在 MySQL 中 Temporary Table 临时表 和 Memory Table 内存表 是两种不同的表类型 它们有一些重要的区别和用途 1 临时表 临时表 Temporary
  • PAA介绍

    ECCV 2020 的一篇文章 论文地址 https arxiv org abs 2007 08103 目录 一 简介 摘要 整个策略流程为 二 相关背景介绍 三 提出的方法 3 1 概率Anchor分配算法 3 2 测试阶段加入预测IoU
  • 我用ChatGPT写2023高考语文作文(一):全国甲卷

    2023年 全国甲卷 适用地区 广西 贵州 四川 西藏 人们因技术发展得以更好地掌控时间 但也有人因此成了时间的仆人 这句话引发了你怎样的联想与思考 请写一篇文章 要求 选准角度 确定立意 明确文体 自拟标题 不要套作 不得抄袭 不得泄露个
  • 怎么修复老照片?给你推荐这几个修复方法

    相信大家的家里都有老照片吧 那在你们翻看这些老照片的时候 有没有发现有些老照片变得有些破旧 泛黄 模糊等情况呢 看到这些情况 大家是不是会很心疼呢 因为这些老照片都充满了各种各样的回忆 根本拍不出第二张同样的照片 但其实我们可以使用软件来修
  • 设计模式原则-开闭原则

    设计模式原则 开闭原则 1 概述 开闭原则 Open Closed Principle 是编程中最基础 最重要的设计原则 一个软件实体如类 模块和函数应该对扩展开放 对提供方 对修改关闭 对使用方 用抽象构建框架 用实现扩展细节 当软件需要
  • 8个Python实用脚本,赶紧收藏

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