新聞中心
學(xué)過(guò)編程的都知道,除了要寫(xiě)代碼,測(cè)試也是很重要的環(huán)節(jié)。大家都只聽(tīng)說(shuō)程序員小哥哥的頭發(fā)是稀有的東西,那如果測(cè)試的速度變快豈不是可以早早下班?今天小編就為大家?guī)?lái)幾個(gè)Python中幾個(gè)實(shí)用的腳本。

衢州ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書(shū)未來(lái)市場(chǎng)廣闊!成為成都創(chuàng)新互聯(lián)公司的ssl證書(shū)銷(xiāo)售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:028-86922220(備注:SSL證書(shū)合作)期待與您的合作!
1.解決 linux 下 unzip 亂碼的問(wèn)題。
import osimport sysimport zipfileimport 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=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='命令對(duì)象.')
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.'), pathif __name__ == '__main__':
argv = sys.argv
main(argv)2.統(tǒng)計(jì)當(dāng)前根目錄代碼行數(shù)。
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)3.掃描當(dāng)前目錄和所有子目錄并顯示大小。
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天以上的所有文件移動(dòng)到目標(biāo)目錄。
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 # 設(shè)置源目錄
dst = args.dst # 設(shè)置目標(biāo)目錄
days = args.days # 設(shè)置天數(shù)
now = time.time() # 獲得當(dāng)前時(shí)間
if not os.path.exists(dst):
os.mkdir(dst)
for f in os.listdir(src): # 遍歷源目錄所有文件
if os.stat(f).st_mtime < now - days * 86400: # 判斷是否超過(guò)240天
if os.path.isfile(f): # 檢查是否是文件
shutil.move(f, dst) # 移動(dòng)文件5.掃描腳本目錄,并給出不同類(lèi)型腳本的計(jì)數(shù)。
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)以上就是Python中有5個(gè)實(shí)用的腳本。更多Python學(xué)習(xí)推薦:PyThon學(xué)習(xí)網(wǎng)教學(xué)中心。
名稱(chēng)欄目:創(chuàng)新互聯(lián)Python教程:Python有哪些實(shí)用的腳本?
當(dāng)前網(wǎng)址:http://m.fisionsoft.com.cn/article/cohsieh.html


咨詢
建站咨詢
