python - 通过套接字接收的总字节数与实际文件大小不同

标签 python sockets ftp ftplib

我编写了一个从 FTP 服务器下载文件的程序,代码如下:

from ftplib import FTP

host = 'x.x.x.x'
user = 'demo'
password = 'fakepw`'
path = '/mnt10/DATA/201605/'
filename = 'DATA.TXT'
ftp = FTP(host, user, password)   # connect to host, default port
ftp.cwd(path)
ftp.voidcmd('TYPE I')
sock = ftp.transfercmd('RETR ' + filename)
f = open('D:\\DATA\\' + filename, 'wb')
chunk = 1
while True:
    block = sock.recv(1024*1024)
    if not block:
        break
    print('Getting file {} bytes'.format(chunk*(1024**2)))
    chunk += 1
    f.write(block)
sock.close()

以下是程序运行结果:

Getting file 1048576 bytes
Getting file 2097152 bytes
Getting file 3145728 bytes
Getting file 4194304 bytes
Getting file 5242880 bytes
..........................
Getting file 22020096 bytes
Getting file 23068672 bytes
Getting file 24117248 bytes
Getting file 25165824 bytes
Getting file 26214400 bytes

Process finished with exit code 0

但实际文件大小只有11.5MB左右 Real file size

我不知道他们为什么不同。

编辑: 正如 @Martin Prikryl 的回答,我已经改变了我的程序,如下所示:

total_size = 0

while True:
    block = sock.recv(1024*1024)
    if not block:
        break
    print('Size of block: {}'.format(len(block)))
    total_size += len(block)
    f.write(block)

print('Total size: {}'.format(total_size))

sock.close()

现在程序运行良好。

Size of block: 1048576
Size of block: 6924
Size of block: 1048576
......................
Size of block: 14924
Size of block: 771276
Total size: 11523750

Process finished with exit code 0

最佳答案

如果套接字是异步的,您不会获得完整的 1024*1024 字节。您只能获得可用的字节数(已收到)。

改为打印 block 的大小,以获得准确的读取字节数。

关于python - 通过套接字接收的总字节数与实际文件大小不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37316261/

相关文章:

python - Nuitka编译PyQt5脚本时出现错误 "implicit module sip"错误

java - 通过套接字接收 Diffie-Hellman key 错误

java - 执行 ftp 时出现错误 "javax.net.ssl.SSLException: 530 Please login with USER and PASS"

python - globals() ['variable' ]=在 .py 文件中设置的值在其他 .py 文件中使用时不反射(reflect)值更改

python - 在 Python 2.5 中创建外观

networking - 我是否需要向 ICANN 注册端口为 "in-use"?

xml - 无法使用 node-ftp 或 jsftp 将 XML 文件上传到 FTP

c# - 我们如何使用 FtpWebRequest 显示上传进度条

python - Keras 分类损失的意义

sockets - HTTP/1.1如何解决TCP重置问题?