python FTP上传
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python FTP上传相关的知识,希望对你有一定的参考价值。
#coding:utf-8
"""
@project: sometest
@file: client.py
@author: Boris Hou
@time: 2018-07-06 17:14:47
"""
import socket
import sys
import os
ip_port = ('127.0.0.1', 9999)
sk = socket.socket()
sk.connect(ip_port)
container = {'key': '', 'data': ''}
while True:
input = raw_input('cmd|path:')
cmd, path = input.split('|')
file_name = os.path.basename(path)
file_size = os.stat(path).st_size
sk.send(cmd + "|" + file_name + '|' + str(file_size))
send_size = 0
f = file(path, 'rb')
Flag = True
while Flag:
if send_size + 1024 > file_size:
data = f.read(file_size - send_size)
Flag = False
else:
data = f.read(1024)
send_size += 1024
sk.send(data)
f.close()
sk.close()
#coding:utf-8
"""
@project: sometest
@file: server.py
@author: Boris Hou
@time: 2018-07-06 16:20:36
"""
import SocketServer
import os
class MyServer(SocketServer.BaseRequestHandler):
def handle(self):
base_path = 'D:/temp/'
conn = self.request
print 'connected...'
while True:
pre_data = conn.recv(1024)
cmd, file_name, file_size = pre_data.split('|') # 获取请求方法、文件名、文件大小
recv_size = 0 # 已经接收文件的大小
file_dir = os.path.join(base_path, file_name) # 上传文件路径拼接
f = file(file_dir, 'wb')
Flag = True
while Flag:
if int(file_size) > recv_size: # 未上传完毕,
data = conn.recv(1024) # 最多接收1024,可能接收的小于1024
recv_size += len(data) # 上传完毕,则退出循环
else:
recv_size = 0
Flag = False
continue
f.write(data) # 写入文件
print 'upload successed.'
f.close()
instance = SocketServer.ThreadingTCPServer(('127.0.0.1', 9999), MyServer)
instance.serve_forever()
以上是关于python FTP上传的主要内容,如果未能解决你的问题,请参考以下文章
python之FTP上传和下载
Python脚本通过FTP上传文件
Python——FTP上传和下载
python网络编程socket模块实现ftp上传下载
python实现ftp上传
Python-Socketserver实现FTP,文件上传下载