Python 实用脚本分享

简介: 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

    #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 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 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
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 re
import requests
from lxml import html as lxml_html
import html
except ImportError:
import HTMLParser
html = HTMLParser.HTMLParser()
import cPickle as pk
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'

(\d+) ', cmt)
problem_urls = ['https://leetcode.com' + url \
for url in re.findall(
r'<a href="(/problems/.+?)"', cmt)]
levels = re.findall(r"<td value='\d
'>(.+?)", 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]
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'
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)
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')
return args
args = handle_args(argv)
x = LeetcodeProblems()
x.args = args
x.run()
7.将 Markdown 转换为 HTML。
from bs4 import BeautifulSoup
import markdown
class MarkdownToHtml:
headTag = ''
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] + ''.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)
    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)
    argv.pop(dirArgIndex)
    argv.pop(dirArgIndex-1)
# 至此,列表 argv 中的元素均是源文件路径
# 遍历所有源文件路径
for filePath in argv:
    # 判断文件路径是否有效
    if os.path.isfile(filePath):
        mth.markdownToHtml(filePath, outputDirectory)
        print('Invalid Path: ' + filePath)

8.文本文件编码检测与转换。
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 = '''
目标编码。支持的编码有:
//代码效果参考:http://www.ezhiqi.com/bx/art_71.html

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

//代码效果参考:http://www.ezhiqi.com/bx/art_4337.html

# 重置检测器
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),

//代码效果参考:http://www.ezhiqi.com/bx/art_4695.html

    '('+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)

A thousand journey is started by taking the first step.

相关文章
|
8天前
|
Python
用python转移小文件到指定目录并压缩,脚本封装
这篇文章介绍了如何使用Python脚本将大量小文件转移到指定目录,并在达到大约250MB时进行压缩。
23 2
|
14天前
|
运维 Prometheus 监控
自动化运维的魔法:使用Python脚本简化日常任务
【8月更文挑战第50天】在数字化时代的浪潮中,自动化运维成为提升效率、减少人为错误的利器。本文将通过一个实际案例,展示如何利用Python脚本实现自动化部署和监控,从而让运维工作变得更加轻松和高效。我们将一起探索代码的力量,解锁自动化运维的神秘面纱,让你的工作环境焕然一新。
129 81
|
3天前
|
机器学习/深度学习 人工智能 运维
自动化运维的魔法:如何利用Python脚本提升工作效率
【9月更文挑战第29天】在数字时代的浪潮中,IT运维人员面临着前所未有的挑战和机遇。本文将通过深入浅出的方式,介绍自动化运维的基本概念、核心价值以及使用Python脚本实现自动化任务的方法。我们将从实际案例出发,探讨如何利用Python简化日常的系统管理任务,提高运维效率,并展望自动化运维的未来趋势。无论你是初学者还是有经验的运维专家,这篇文章都将为你开启一扇通往高效工作方式的大门。
9 2
|
7天前
|
Web App开发 存储 安全
Python编写脚本,打开浏览器输入网址,自动化登陆网站
Python编写脚本,打开浏览器输入网址,自动化登陆网站
13 4
|
9天前
|
运维 监控 Python
自动化运维:使用Python脚本简化日常任务
【9月更文挑战第23天】在本文中,我们将探索如何通过编写Python脚本来自动化常见的系统管理任务,从而提升效率并减少人为错误。文章将介绍基础的Python编程概念、实用的库函数,以及如何将这些知识应用于创建有用的自动化工具。无论你是新手还是有经验的系统管理员,这篇文章都将为你提供有价值的见解和技巧,帮助你在日常工作中实现自动化。
|
11天前
|
运维 监控 安全
自动化运维:使用Python脚本简化日常任务
【9月更文挑战第21天】在快速迭代的软件开发环境中,运维工作往往因为重复性高、易出错而被诟病。本文将介绍如何通过编写简单的Python脚本来自动化这些日常任务,从而提升效率和减少错误。我们将以实际案例为基础,展示如何从零开始构建一个自动化脚本,并解释其背后的原理。文章旨在启发读者思考如何利用编程技能来解决工作中的实际问题,进而探索技术与日常工作流程结合的可能性。
|
7天前
|
Python Windows
python之windows脚本启动bat
python之windows脚本启动bat
|
29天前
|
存储 Shell 区块链
怎么把Python脚本打包成可执行程序?
该文档介绍了如何将Python脚本及其运行环境打包成EXE可执行文件,以便在不具备Python环境的计算机上运行。首先确保Python脚本能够正常运行,然后通过安装PyInstaller并使用`--onefile`参数将脚本打包成独立的EXE文件。此外,还提供了去除命令行窗口和指定可执行文件图标的详细方法。这些步骤帮助用户轻松地将Python程序分发给最终用户。
怎么把Python脚本打包成可执行程序?
|
8天前
|
运维 监控 Python
自动化运维:使用Python脚本实现日常任务
【9月更文挑战第24天】在现代的软件开发周期中,运维工作扮演着至关重要的角色。本文将介绍如何利用Python编写简单的自动化脚本,来优化和简化日常的运维任务。从备份数据到系统监控,Python的易用性和强大的库支持使其成为自动化运维的首选工具。跟随这篇文章,你将学习如何使用Python编写自己的自动化脚本,提高运维效率,减少人为错误,并最终提升整个开发流程的质量。
|
17天前
|
存储 程序员 开发者
Python 编程入门:从零基础到编写实用脚本
【9月更文挑战第15天】本文是一篇面向初学者的Python编程入门指南,通过浅显易懂的语言和实际的代码示例,引导读者逐步掌握Python的基本概念、语法规则以及如何运用Python解决实际问题。文章不仅介绍了Python的基础知识点,还通过实例演示了如何将这些知识应用于日常编程任务中,帮助读者快速上手并能够独立编写简单的Python脚本。
下一篇
无影云桌面