BT-makemetainfo-源代码阅读

晚上花了一点时间读了点代码,4.03版本,简单一些,做种的模块叫btmaketorrent.py,但是只有几句,是调用bittorrent/makemetafile.py,其中的逻辑都在这个文件中,没有gui的部分。

def make_meta_files(url, files, flag=Event(), progressfunc=dummy,
filefunc=dummy, piece_len_pow2=None, target=None,
comment=None, filesystem_encoding=None):
def make_meta_file(path, url, piece_len_exp, flag=Event(), progress=dummy,
comment=None, target=None, encoding='ascii'):
def makeinfo(path, piece_length, flag, progress, encoding):

其中核心的方法有这三个,前两个是做预处理和调用第三个makeinfo。


#getfilesystemencoding()
# Return the name of the encoding used to convert Unicode filenames into system file names, or None if the system default encoding is used. The result value depends on the operating system:
# * On Windows 9x, the encoding is ``mbcs''.
# * On Mac OS X, the encoding is ``utf-8''.
# * On Unix, the encoding is the user's preference according to the result of nl_langinfo(CODESET), or None if the nl_langinfo(CODESET) failed.
# * On Windows NT+, file names are Unicode natively, so no conversion is performed. getfilesystemencoding() still returns 'mbcs', as this is the encoding that applications should use when they explicitly want to convert Unicode strings to byte strings that are equivalent when used as file names.


作者使用了一些措施来保证filesystem的编码是否正确,防止encoding错误的情况下会出现找不到文件的情况。
print  sys.getfilesystemencoding()


在我的机器上是mbcs,大概是ms的代码吧。

另外,把几个range定义为无效的字符:
range(0xD800, 0xE000)
range(0xFDD0, 0xFDF0)
range(0xFFFE, 0xFFFF)
使用string的translate方法除去再和原来的比较,如果不等于说明文件名中含有无效的字符,不能生成metainfo。

然后生成头信息:

data = {'info': info, 'announce': url.strip(),'creation date': int(time())}
data['comment'] = comment


作者的递归算法写的比较奇怪,下面是我的ruby代码

puts "Total size of file is #{File.size(file)}"
digest_hash={}
i=1
#generate digest of every piece and put them into
while i<=File.size(file)/(piece_length) do
block = file.sysread(piece_length)
digest = Digest::MD5.hexdigest(block)
puts digest+" "+i.to_s
digest_hash.store(i, digest)
i+=1
end
i-=1
last=File.size(file)-piece_length*i
puts "The last block size is #{last}"
block =file.sysread(last)
digest = Digest::MD5.hexdigest(block)
i+=1
puts "last one is #{digest}, #{i}"
digest_hash.store(i, digest)

这里只考虑到一个文件的情况,每次取piece_len,然后用digest_hash去生成摘要。

Python的语法非常简单,以前没有接触过,只是边看代码边参考python2.5的手册和[url]docs.python.org[/url]就可以很好的理解。

贴一点看到的比较好玩的代码:


dict={"a":2,"b":3,"c":54,"d":5}

def print4(a,b,c,d):
print a,b,c,c

print4(**dict)


还有

piece_length = 2 ** piece_len_exp


2的exp次幂。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值