8個Python實用腳本,趕緊收藏

来源:https://www.cnblogs.com/chengxuyuanaa/archive/2020/04/17/12720067.html
-Advertisement-
Play Games

腳本寫的好,下班下得早!程式員的日常工作除了編寫程式代碼,還不可避免地需要處理相關的測試和驗證工作。 例如,訪問某個網站一直不通,需要確定此地址是否可訪問,伺服器返回什麼,進而確定問題在於什麼。完成這個任務,如果一味希望採用編譯型語言來編寫這樣的代碼,實踐中的時間和精力是不夠的,這個時候就需要發揮腳 ...


腳本寫的好,下班下得早!程式員的日常工作除了編寫程式代碼,還不可避免地需要處理相關的測試和驗證工作。

例如,訪問某個網站一直不通,需要確定此地址是否可訪問,伺服器返回什麼,進而確定問題在於什麼。完成這個任務,如果一味希望採用編譯型語言來編寫這樣的代碼,實踐中的時間和精力是不夠的,這個時候就需要發揮腳本的神奇作用!

這裡還要註意:不管你是為了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教程項目,還可以跟老司機交流討教!
本文的文字及圖片來源於網路加上自己的想法,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯繫我們以作處理。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 程式每次讀入一個正3位數,然後輸出按位逆序的數字。註意:當輸入的數字含有結尾的0時,輸出不應帶有前導的0。比如輸入700,輸出應該是7。輸入格式:每個測試是一個3位的正整數。輸出格式:輸出按位逆序的數。代碼如下:#!/usr/bin/python# -*- coding: utf-8 -*-n = ... ...
  • 配置視圖解析器 在前面的章節中,我們已經把 中使用到的註解已經全部講解過了。但是 中的代碼存在了一個問題,那就是返回值跳轉的頁面地址太繁瑣了。假設我們所有的頁面都放在 下,那我們是不是每次都得覆寫很多遍 ,這是作為一個優秀的程式猿不可以忍耐的!我們想要只要 return 我們需要改變的值就可以了,那 ...
  • 使用 @RequestParam 將請求參數綁定至方法參數 你可以使用 註解將請求參數綁定到你控制器的方法參數上。 下麵這段代碼展示了它的用法: 若參數使用了該註解,則該參數預設是必須提供的,但你也可以把該參數標註為非必須的:只需要將 註解的 屬性設置為 即可: 註意:這裡使用的 是將請求的參數設置 ...
  • 項目簡介 項目來源於: "https://gitee.com/darlingzhangsh/graduation_project" 本系統是基於 Thymeleaf+SpringBoot+Mybatis 。是非常標準的SSM三大框架( SpringBoot就是一個大框架,裡面包含了許多的東西,其中S ...
  • 這一節雖然簡單,但是很繁瑣,可以先瞭解 @RequestMapping 的使用,不是很明白也沒有關係,先繼續往下學習,等你回頭再看一遍的時候,你會發現 @RequestMapping 竟然是如此的簡單! @RequestMapping @RequestMapping可以在控制器 類 上或者控制器 方 ...
  • 0 遇到過得反爬蟲策略以及解決方法? 1.通過headers反爬蟲 2.基於用戶行為的發爬蟲:(同一IP短時間內訪問的頻率) 3.動態網頁反爬蟲(通過ajax請求數據,或者通過JavaScript生成) 4.對部分數據進行加密處理的(數據是亂碼) 解決方法: 對於基本網頁的抓取可以自定義header ...
  • Django 的表單處理:視圖獲取請求,執行所需的任何操作,包括從模型中讀取數據,然後生成並返回HTML頁面(從模板中),我們傳遞一個包含要顯示的數據的上下文。使事情變得更複雜的是,伺服器還需要能夠處理用戶提供的數據,併在出現任何錯誤時,重新顯示頁面。 下麵顯示了 Django 如何處理表單請求的流 ...
  • @Controller 與 @RestController 的區別 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...