簡體   English   中英

將python2腳本轉換為python3

[英]Convert python2 script to python3

想讓這個腳本與python3(Python 3.10.4)一起工作: https://stackoverflow.com/a/2573715/2394635

它會在下面顯示完整代碼:

我沒有直接放代碼,因為我收到了stackoverflow通知It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details.

我使用了 pip 腳本2to3 ,結果代碼如下:

import sys, os, hashlib, io, bencode

def pieces_generator(info):
    """Yield pieces from download file(s)."""
    piece_length = info['piece length']
    if 'files' in info: # yield pieces from a multi-file torrent
        piece = ""
        for file_info in info['files']:
            path = os.sep.join([info['name']] + file_info['path'])
            print(path)
            sfile = open(path.decode('UTF-8'), "rb")
            while True:
                piece += sfile.read(piece_length-len(piece))
                if len(piece) != piece_length:
                    sfile.close()
                    break
                yield piece
                piece = ""
        if piece != "":
            yield piece
    else: # yield pieces from a single file torrent
        path = info['name']
        print(path)
        sfile = open(path.decode('UTF-8'), "rb")
        while True:
            piece = sfile.read(piece_length)
            if not piece:
                sfile.close()
                return
            yield piece

def corruption_failure():
    """Display error message and exit"""
    print("download corrupted")
    exit(1)

def main():
    # Open torrent file
    torrent_file = open(sys.argv[1], "rb")
    metainfo = bencode.bdecode(torrent_file.read())
    info = metainfo['info']
    pieces = io.StringIO(info['pieces'])
    # Iterate through pieces
    for piece in pieces_generator(info):
        # Compare piece hash with expected hash
        piece_hash = hashlib.sha1(piece).digest()
        if (piece_hash != pieces.read(20)):
            corruption_failure()
    # ensure we've read all pieces 
    if pieces.read():
        corruption_failure()

if __name__ == "__main__":
    main()

但是,一直失敗:

% python3 extract-torrent.py archive.torrent 
Traceback (most recent call last):
  File "/home/smt/Documents/extract-torrent-py3.py", line 1, in <module>
    import sys, os, hashlib, io, bencode
  File "/home/smt/.local/lib/python3.10/site-packages/bencode.py", line 73, in <module>
    from types import StringType, IntType, LongType, DictType, ListType, TupleType
ImportError: cannot import name 'StringType' from 'types' (/usr/lib/python3.10/types.py)

有什么幫助嗎?

正如@9769953 所指出的, bencode與 Python 3.10 不兼容。 您可以嘗試聲稱bencodepy 2 和 3 兼容的 bencodepy。

網站

  1. 使用pip install bencode.py
  2. 使用import bencodepy

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM