geekcomputers学习--适合python新手的系统库例子

geekcomputers利用了python实现了许多常用的功能,而且它的每个脚本都十分短小,是便于新手学习的好工具。我翻译/加了详尽的注释。

《geekcomputers学习--适合python新手的系统库例子》 geekComputer

备份目录

import shutil                           
# 加载库
import datetime                     
# 加载库
import os                               
# 加载库

today = datetime.date.today()     
# 得到今天的日期,是一个datetime.date对象
todaystr = today.isoformat()        
# 格式化得到类似'2016-09-30'的字符串

confdir = os.getenv("my_config")            
# 获取系统环境变量
dropbox = os.getenv("dropbox")                  
# 获取系统环境变量
conffile = ('services.conf')                    
# 设置变量为配置文件名
conffilename = os.path.join(confdir, conffile)               
# 将文件目录和文件名连起来
sourcedir = os.path.expanduser('~/Library/Services/')            
# 要被备份的文件目录
destdir = os.path.join(dropbox, "My_backups"+"/"+"Automater_services"+todaystr+"/")   
# 生成备份目的目录
                  
                                                                                    
for file_name in open(conffilename):                                      
# 遍历配置文件
  fname = file_name.strip()                                                     
  # 去除配置文件的空行
  if fname:
  # 对非空行进行操作
    sourcefile = os.path.join(sourcedir, fname)     
    # 获取要备份的源文件名/文件目录名
    destfile = os.path.join(destdir, fname)             
    # 生成目的文件名/文件目录名
    shutil.copytree(sourcefile, destfile)                                   
    # 迭代拷贝目录或文件

批量重命名

__author__ = 'Craig Richards'
__version__ = '1.0'
#作者和版本信息

import os
import sys
# 加载库

def batch_rename(work_dir, old_ext, new_ext):
    '''
    批量修改文件拓展名,从old_ext到new_ext
    '''
    # 遍历当前目录下所有内容
    for filename in os.listdir(work_dir):
        # 得到文件拓展名
        file_ext = os.path.splitext(filename)[1]
        # 查看文件拓展名是否是需要修改的拓展名
        if old_ext == file_ext:
            # 将旧文件名中的拓展名替换为新拓展名
            newfile = filename.replace(old_ext, new_ext)
            # 对文件重命名
            os.rename(
              os.path.join(work_dir, filename),
              os.path.join(work_dir, newfile)
            )


def main():
    '''
    如果文件被直接运行main函数将被调用
    '''
    # 将系统传入的第一个变量设为工作目录(这里将argv[0]当做第零个,argv[0]是脚本名)
    work_dir = sys.argv[1]
    # 将系统传入的第二个变量设为旧拓展名
    old_ext = sys.argv[2]
    # 将系统传入的第三个变量设为新拓展名
    new_ext = sys.argv[3]
    batch_rename(work_dir, old_ext, new_ext)


if __name__ == '__main__':
    main()

检查文件是否存在是否可以读取

import sys      
import os       
# 加载库

def readfile(filename):
    with open(filename, 'r') as f:      
  # 使用with语句确保文件在任何情况下正确关闭
        line = f.read()
      # 读取文件内容
    print line

def main():
  if len(sys.argv) == 2:        
  # 检查传入脚本的参数是否是两个
    filename = sys.argv[1]      
    # argv[0]是脚本名,argv[1]是文件名
    if not os.path.isfile(filename):    
    # 检查文件是否存在
      print '[-] ' + filename + ' does not exist.'
      exit(0)
    if not os.access(filename, os.R_OK):    
    # 检查当前用户是否具有可读权限
      print '[-] ' + filename + ' access denied'
      exit(0)
  else:
    print '[-] Usage: ' + str(sys.argv[0]) + ' <filename>' 
    # 如果传入参数不正确则提示用法
    exit(0)
  print '[+] Reading from : ' + filename    
  # 提示开始读取文件
  readfile(filename)
  
if __name__ == '__main__':
  main()

检查当前目录及其所有子文件是否有数据库文件

import os

def isSQLite3(filename):
# 检查是否为SQLite3数据库文件
    from os.path import isfile, getsize
    # 加载库
    if not isfile(filename):
    # 检查是否存在文件
        return False
    if getsize(filename) < 100: 
    # SQLite 数据库文件头是100字节
        return False
    else:
        Header = open(filename, 'rb').read(100)
        # 以字节流可读打开文件,并读取前100字节
        fd.close()
        # 关闭文件
        if Header[0:16] == 'SQLite format 3\000':
        # 判断文件头是否符合SQLite3标准
        # \000就表示一个数值为0的字符,它只占一个字节,也就是0x00
            return True
        else:
            return False

log=open('sqlite_audit.txt','w')
# 在当前目录创建一个文件做记录
for r,d,f in os.walk(r'.'):
# 递归遍历当前目录中所有文件,以(当前目录,当前目录下的子目录,当前目录下的文件名)的形式返回
  for files in f:
    # 遍历当前目录下的文件
    if isSQLite3(files):
      # 调用函数判断你是否为SQLite3文件
      print files
      print "[+] '%s' **** is a SQLITE database file **** " % os.path.join(r,files)
      # 将当前路径和文件名连接打印出完整路径
      log.write("[+] '%s' **** is a SQLITE database file **** " % files+'\n')
      # 写入文件
    else:
      log.write("[-] '%s' is NOT a sqlite database file" % os.path.join(r,files)+'\n')
      log.write("[-] '%s' is NOT a sqlite database file" % files+'\n')

检查网络连接

import urllib.request
# 加载库
try:
    urllib.request.urlopen("https://www.google.com.hk", timeout=2)
    # 使用urlopen尝试打开google,超时为两秒
    print("working connection")
except urllib.request.URLError:
    # 如果出现异常,打印输出
    print("No internet connection")

字符串字母统计

import pprint
info = '''
WESTMORELAND
The prince is here at hand: pleaseth your lordship
To meet his grace just distance 'tween our armies.
MOWBRAY
Your grace of York, in God's name then, set forward.
ARCHBISHOP OF YORK
Before, and greet his grace: my lord, we come.
Exeunt'''
# 待统计的大字符串
count = { }
# 创建一个空字典用于存储
for character in info.upper():
# 对大字符串使用小写变大写函数,然后遍历每一个字符 
    count.setdefault(character, 0)
    # 设置字典该键的默认值为0
    count[character] = count[character]+1
    # 将相应字符的字典值加1

value = pprint.pformat(count)
# pprint实现格式更好的输出
print(value)

《geekcomputers学习--适合python新手的系统库例子》 字符统计输出结果

检查是否存在测试文件夹,不存在则创建它

import os       
# 导入系统模块
try:
    home = os.path.expanduser("~")          
    # 获得用户目录
    print(home)                           
    # 打印它
    
    if not os.path.exists(home+'/testdir'):
    # 检查当前用户目录是否存在testdir目录
        os.makedirs(home+'/testdir')        
        # 不存在则创建它
except Exceptions as e:
# 如果出现异常则将异常字符串赋给变量e然后打印它
    print (e)

加载一系列日常任务

import platform     
import os
import subprocess
import sys
# 加载库
from time import strftime       
# 只加载time库的strftime模块

def clear_screen():             
# 清屏函数
    if os.name == "posix":      
    # 判断系统是Unix/Linux/MacOS/BSD/etc
        os.system('clear')      
        # 清屏
    elif os.name in ("nt", "dos", "ce"):    
    # DOS/Windows
        os.system('CLS')                    
        # 清屏

def print_docs():                           
# 自动打印每日检查
  print( "Printing Daily Check Sheets:")
  # 下面的代码构建子进程传递命令行字符串来打开word,打开文档,打印输出它然后关闭
  subprocess.Popen(["C:\\Program Files\Microsoft Office\Office16\winword.exe", "D:\\test.docx", "/mFilePrintDefault", "/mFileExit"]).communicate()  
  # communicate()是Popen对象的一个方法,该方法会阻塞父进程,直到子进程完成,这里不执行通信,仅仅是等待子进程完成退出。

def putty_sessions():
# 打开putty的函数
  for server in open(conffilename):         
  # 遍历文件中的服务器列表
    subprocess.Popen(('putty -load '+server))   
    # 打开相应的PuTTY回话

def rdp_sessions():
  print( "Loading RDP Sessions:")
  subprocess.Popen("mstsc eclr.rdp")        
  # 按指定配置打开一个终端会话连接
  
def euroclear_docs():
  # 打开IE加载文档
  subprocess.Popen('"C:\\Program Files\\Internet Explorer\\iexplore.exe"' '"file://fs1\pub_b\Pub_Admin\Documentation\Settlements_Files\PWD\Eclr.doc"')
        

# 开始主函数
def main():
    filename = sys.argv[0]                          # 获取当前脚本文件名
    confdir = os.getenv("my_config")                # 获取系统环境变量
    conffile = ('daily_checks_servers.conf')        # 设置配置文件名
    conffilename = os.path.join(confdir, conffile)  # 生成配置文件完整路径
    clear_screen()                                  # 使用清屏函数

    # 生成问候信息以及系统信息
    print( "Good Morning " + os.getenv('USERNAME') + ", " + filename, "ran at", strftime("%Y-%m-%d %H:%M:%S"), "on",platform.node(), "run from",os.getcwd())

    print_docs()                                    # 调用上面定义的函数
    putty_sessions()                                
    rdp_sessions()                                  
    euroclear_docs()                                

if __name__ == '__main__':
    main()

《geekcomputers学习--适合python新手的系统库例子》 。。。

未完待续。。。

    原文作者:treelake
    原文地址: https://www.jianshu.com/p/5754e150bdb6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞