0

我制作了一个脚本,它将映射我一个目录并给我关于它的统计信息......这是脚本:

import os 
import hashlib
import platform
import sys
import argparse
import HTML

class Map(object):

    def __init__(self,param):
        self.param_list = param
        self.slash = self.slash_by_os()
        self.result_list = []
        self.os = ""


    def calc_md5(self,file_path):
        with open(file_path) as file_to_check:
            data = file_to_check.read()    
            md5_returned = hashlib.md5(data).hexdigest()

        return md5_returned

    def slash_by_os(self):
        general_id = platform.system()
        actual_os = ""

        if general_id == "Darwin" or general_id == "darwin":
            actual_os = "UNIX"
        elif general_id == "Linux" or general_id == "linux":
            actual_os = "UNIX"
        elif general_id  == "SunOS":
            actual_os = "UNIX"
        elif general_id == "Windows" or general_id == "windows":
            actual_os = "WIN"
        else:
            actual_os = general_id

        if actual_os == "UNIX":
            return '/'
        elif actual_os == "WIN":
            return '\\'
        else:
            return '/'

        self.os = actual_os

    def what_to_do(self,new_dir):
        act = []
        act.append(new_dir[:-1])
        for param in self.param_list:
            if param == "md5":
                x = self.calc_md5(new_dir[:-1])
                act.append(x)
            elif param == "size":
                x = os.stat(new_dir[:-1]).st_size
                act.append(x)
            elif param == "access":
                x = os.stat(new_dir[:-1]).st_atime
                act.append(x)
            elif param == "modify":
                x = os.stat(new_dir[:-1]).st_mtime
                act.append(x)
            elif param == "creation":
                    x = os.stat(new_dir[:-1]).st_ctime
                    act.append(x)   

        return act

    def list_of_files(self ,dir_name ,traversed = [], results = []): 

        dirs = os.listdir(dir_name)
        if dirs:
            for f in dirs:
                new_dir = dir_name + f + self.slash
                if os.path.isdir(new_dir) and new_dir not in traversed:
                    traversed.append(new_dir)
                    self.list_of_files(new_dir, traversed, results)
                else:
                    act = self.what_to_do(new_dir)
                    results.append(act)
        self.result_list = results  
        return results


def parse_args():
    desc = "Welcom To dirmap.py 1.0"
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument('-p','--path', help='Path To Original Directory', required=True)
    parser.add_argument('-md','--md5', action = 'store_true',help='Show md5 hash of file', required=False)
    parser.add_argument('-s','--size', action = 'store_true', help='Show size of file', required=False)
    parser.add_argument('-a','--access', action = 'store_true',  help='Show access time of file', required=False)
    parser.add_argument('-m','--modify', action = 'store_true', help='Show modification time of file', required=False)
    parser.add_argument('-c','--creation', action = 'store_true', help='Show creation of file', required=False)

    args = vars(parser.parse_args())

    params = []
    for key,value in args.iteritems():
        if value == True:
            params.append(key)

    return args,params



def main():
    args , params = parse_args() 
    dir_path = args['path']
    map = Map(params)
    dir_list = map.list_of_files(dir_path)

    params.insert(0,"path")


    htmlcode_dir = HTML.table(dir_list,header_row=params)
    print htmlcode_dir

main()

在linux env上运行时,我得到了这个回溯:

MacBook-Pro:Python 脚本 Daniel$ python dirmap.py -p / -md -s -a -m -c >> 1.html Traceback(最近一次调用最后):文件“dirmap.py”,第 132 行,在 main () 文件“dirmap.py”,第 124 行,在 main dir_list = map.list_of_files(dir_path) 文件“dirmap.py”,第 89 行,在 list_of_files act = self.what_to_do(new_dir) 文件“dirmap.py”,行61,在 what_to_do x = self.calc_md5(new_dir[:-1]) 文件“dirmap.py”,第 25 行,在 calc_md5 中,open(file_path, 'rb') as file_to_check: IOError: [Errno 102] Operation not supported在套接字上:'/.dbfseventsd'

我该如何解决我的问题?谢谢 !

4

1 回答 1

1

问题是当 open() 在扫描各种文件时在套接字上运行时。您应该能够通过捕获 IOError 来使用 try/catch 解决此问题。例子:

try:
    with open(file_path) as file_to_check:
        data = file_to_check.read()    
        md5_returned = hashlib.md5(data).hexdigest()
except IOError as ioe:
    print "Failed: " + str(ioe)

但这将捕获所有 io 错误,而不仅仅是套接字。如果您想要处理此特定场景的错误消息,您需要在尝试打开它之前检查这是否是一个套接字。有关如何检查文件是否为套接字的信息,请参阅this 。

另外,我注意到您正在手动检查要使用哪个文件分隔符的平台。它内置为“os.path.sep”。查看 python os.path模块,了解更多独立于平台的遍历文件系统的方法。

于 2014-04-05T03:03:26.350 回答