2009-11-11

    我的第一个python脚本 - [python]

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
    http://bbayou.blogbus.com/logs/50994895.html

    呵呵,最近在学习python,只明白了大概,很多还不会,不熟悉。现在放一个python程序,目标是:遍历文件夹里的torrent文件,分析hash info 加密后是否跟原文件的文件名相同,不同的话,记录log文件。我写起来有点复杂,感觉还不是按照python的思维来写程序,要学的还很多。

    #! /usr/bin/python

    from sys import *
    from bencode import *
    import hashlib
    import os
    import os.path

    #-----test-----
    #if len(argv) != 2:
    #    print "ERROR: use ./33.py filename"
    #    exit(2)
    #file_name = argv[1]
    #-----test-----

    def check_torrent_hash(file_name):
        filename ='torrent/'+file_name
        metainfo_file = open(filename, 'rb')
        if metainfo_file:
            metainfo = bdecode(metainfo_file.read())
        else:
            print "ERROR: Not a valid torrent file"
            exit(1)
        metainfo_file.close()
        info = metainfo['info']
        hahaha =  bencode(info)
        mySha1 = hashlib.sha1()   
        mySha1.update(hahaha)
        mySha1_Digest = mySha1.hexdigest()
        up_str = mySha1_Digest.upper();
        OK = file_name.split('.')   
        #print up_str
        #print OK[0]
        if not up_str==OK[0]:
            error_file = open('/home/changyou/wget/error.log', 'a+')
            error_file.writelines(up_str+'\n')
            error_file.close()
            return 'NO~~please check /home/changyou/wget/error.log'
        else:
            return 'OK!!!'

    rootdir = "/home/changyou/wget/torrent/"
    for parent, dirnames, filenames in os.walk(rootdir):
        for filename in filenames:
            print check_torrent_hash(filename)


     


    收藏到:Del.icio.us




    引用地址: