Python有哪些实用的脚本

540次阅读
没有评论
Python有哪些实用的脚本

学过编程的都知道,除了要写代码,测试也是很重要的环节。大家都只听说程序员小哥哥的头发是稀有的东西,那如果测试的速度变快岂不是可以早早下班?今天小编就为大家带来几个Python中几个实用的脚本。

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

import osimport sysimport zipfileimport argparses = 'x1b[%d;%dm%sx1b[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.'), pathif __name__ == '__main__':
    argv = sys.argv
    main(argv)

 

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

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.扫描当前目录和所有子目录并显示大小。

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:logsputtylogs"          
zipdir="c:logsputtylogszipped_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个实用的脚本。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-04发表,共计4891字。
新手QQ群:570568346,欢迎进群讨论 Python51学习