IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> python multiprocessing ftp/http download -> 正文阅读

[网络协议]python multiprocessing ftp/http download

from ctypes.wintypes import DOUBLE
from multiprocessing import Pool
import os, time, random
from ftplib import FTP
import datetime
#from ftplibnsf import FTP
import os, time
import multiprocessing
import gc
import threading
import sys
import random,  requests

SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],

             1024 :   [ 'KiB' ,   'MiB' ,   'GiB' ,   'TiB' ,   'PiB' ,   'EiB' ,   'ZiB' ,   'YiB' ]} 
 
def  approximate_size ( size ,  a_kilobyte_is_1024_bytes = True ): 
    '''Convert a file size to human-readable form.
 
     Keyword arguments:
     size -- file size in bytes
     a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
                                 if False, use multiples of 1000
 
     Returns: string
 
    ''' 
    
    if  size  <   0 : 
          raise   ValueError ( 'approximate_size: number must be non-negative' ) 
 
    multiple  =   1024   if  a_kilobyte_is_1024_bytes  else   1000 
    for  suffix  in  SUFFIXES [ multiple ]: 
        size  /=  multiple
        if  size  <  multiple : 
              return   '{0:.1f} {1}' . format ( size ,  suffix ) 
 
    raise   ValueError ( 'approximate_size: number too large' )


urllist=[]
def getUrlList():
    with open('url.txt','r') as f:
        for line in f:
            urllist.append(list(line.strip('\n').split(',')))
    print(urllist)

#lock = threading.RLock()
lastTime = datetime.datetime.now()
lasttotal =0
#global nump
nump = 0
#def printdata(data):
#    print(datetime.datetime.now(),"   ", len(data))
#total = 0
def getnump():
    while True:
        ten=input("请输入进程数量(1-99):")
        try:
            x=eval(ten)
            if (type(x)==int) and (x in range(0, 100)):
                break
        except:
                pass
    return x

def getcontent_length(content_length):
    try:
        x=eval(content_length)
        if (type(x)==int) :
            return x
    except:
            return 0
    return 0


speed = 0
starttime = datetime.datetime.now()
def worker(urllist, i, l, totalOfTotal, nump):

    
    def printdata(data, content_length,  total, url, l, totalOfTotal, nump ):
        
        lendata = len(data)
        #puttotalOfTotal(totalOfTotal)
        #global total
        #global lock
        global lastTime, lasttotal, speed, starttime
        #global nump
        l.acquire()
        try:

            #total = total + lendata
            content_length = max(content_length, 1)
            thistime = datetime.datetime.now()
            interval = int(max(nump/2, 1))
            #print('intervalllllllllllllllllllllllllllllllllllllll',nump, interval)
            total_seconds = max(1, (thistime - lastTime ).total_seconds())
            start_seconds = max(1, (thistime - starttime ).total_seconds())
            if start_seconds < interval :
                speed = (total- lasttotal)/start_seconds
            
            if ( (thistime - lastTime ).total_seconds() > interval):
                speed = (total- lasttotal)/interval

                print(strpid, thistime,"   ", lendata, "   ",
                    approximate_size(speed),'/S',start_seconds, 'seconds',
                    approximate_size(content_length), 'percent: {:.2%}'.format(total/content_length), url,
                    approximate_size(lasttotal), approximate_size(total), approximate_size(totalOfTotal.value))
                if (speed > 600000):
                    print('=============================================')
                lastTime = thistime
                lasttotal = total
        except Exception as e:
            print('printdata:', url, str(e))
        
        finally:
            # 修改完成,释放锁
            l.release()

    total = 0
    try:
        while 1:
            port = 21
            #ftp = FTP()  # 设置变量
            timeout = 22
            
            #total = 0
            strpid = "进程号" + str(os.getpid()) + ' '+ str(i)+': '
            #global urllist
            rlist = random.randint(1,len(urllist))-1
            rurl = urllist[rlist]

            print(strpid, 'random:', rlist, ' ', rurl )
            #print(strpid,": connecting ", ts_ip)
            #print(strpid, ftp.connect(ts_ip, port, timeout))
            #ftp.login(user, pwd)
            #ftp.cwd("")
            #localname = "CPE_D_" + str(msg) + ".rar"
            #print("进程号:" + str(os.getpid()) + " 开始下载 " + localname)
            try:
                #f = open(localname, 'wb')
                filename = 'RETR ' + "1G.rar"
                #print(rurl, rurl[0])
                #r = requests.get( url='https://releases.ubuntu.com/20.04/ubuntu-20.04.3-desktop-amd64.iso',  stream=True        )
                r = requests.get( url=rurl[0],  stream=True        )
                print(strpid, rurl, r.headers, r.headers.get('content-length') )
                content_length = 0
                content_length = getcontent_length(r.headers.get('content-length'))
                #total = 0
                global lasttotal, starttime, uplimit
                lasttotal = 0
                starttime = datetime.datetime.now()
                

                for chunk in r.iter_content(chunk_size=1024):
                    if chunk:
                        total = total + len(chunk)
                        totalOfTotal.value = totalOfTotal.value + len(chunk)
                        printdata(chunk,content_length, total, rurl, l, totalOfTotal, nump)
                        global speed 
                        total_seconds = max((datetime.datetime.now()- starttime).total_seconds(), 1)

                        #speed = int(total/total_seconds)
                        if (total_seconds>22) and(total>10000000) and (speed < 600000):
                            break
                        if (total_seconds>55) and (speed < 100000):
                            break
                        if total>content_length:
                            break
                        if totalOfTotal.value >uplimit:
                            break
                #ftp.retrbinary(filename, f.write)
                #ftp.retrbinary(filename, printdata)
                #f.close()  # 关闭文件
            except Exception as e:
                print(e.args)
                print(strpid, rurl, str(e))
                print(repr(e))
                #print("进程号:" + str(os.getpid()) + " 下载中断  " )
                #f = open(localname, 'rb')
                #f.close()
                #print("进程号:" + str(os.getpid()) + " 中断处理完成  " + localname)

                # print("进程号:" + str(os.getpid()) + " 下载文件完成:" + localname)
            time.sleep(3)
            print("进程号:" + str(os.getpid()) + " done!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!  " ,  'speed:',
                approximate_size(speed),'/S',approximate_size(total),total_seconds,'seconds', rurl)
            # print(localname)
    except Exception as e:        
        print('printdata:', rurl, str(e))
        f=open('error.txt', 'a+')
        f.write(str(datetime.datetime.now())+"进程号:" + str(os.getpid())+' '+'speed:'+
                approximate_size(speed)+'/S '+approximate_size(total)+str(total_seconds) +'seconds'+ rurl)
        f.close

def puttotalOfTotal(totalOfTotal):
#totalOfTotal = 0
    global totalOfTotalname
    with open(totalOfTotalname,'w') as f:
        f.write(str(totalOfTotal.value))


totalOfTotalname = 'totalOfTotal.txt'
def gettotalOfTotal():
    #totalOfTotal = 0
    global totalOfTotalname
    if os.path.exists(totalOfTotalname):
        with open(totalOfTotalname,'r') as f:
            s = f.read()
            print('s', s)
            #i = int(s)
            #print('i', i)
            return(s)
    return '0' 

uplimit = 8400000000000
if __name__ == '__main__':
# while 1:
    try:
        multiprocessing.freeze_support()
        getUrlList()
        
        if os.path.exists(os.getcwd()):
            s_list = os.listdir(os.getcwd())
        for s_list_line in s_list:
            if "CPE_D_" in s_list_line:
                # print(os.getcwd() +"\\" +s_list_line)
                os.remove(os.getcwd() + "\\" + s_list_line)
        
        nump = getnump()
        #po = Pool(nump)  # 最大的进程数
        #for i in range(0, 10000000000):
        #    po.apply_async(worker, (urllist, ))
            # po.map(worker, (i,))
        plist = []
        lock = multiprocessing.Lock()
        totalOfTotal = multiprocessing.Value('d', 0)
        totalOfTotal.value = float(gettotalOfTotal())
        print('gettotalOfTotal()', totalOfTotal.value)
        for i in range(nump):
            p = multiprocessing.Process(target=worker, args=(urllist,i, lock, totalOfTotal, nump))
            p.start()
            plist.append(p)

            gc.collect()
        while 1:
            time.sleep(11)
            puttotalOfTotal(totalOfTotal)
            active_children = len(multiprocessing.active_children())
            print('multiprocessing.active_childrennnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn()', active_children)
            if active_children < nump :
                p = multiprocessing.Process(target=worker, args=(urllist,active_children, lock, totalOfTotal, nump))
                p.start()
                plist.append(p)
            gc.collect()
        po.close()
        po.join()
    except Exception as e:
        print('__main__', str(e))
        time.sleep(2)
# pyinstaller -F   ftp_NR_CPE_B.py

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-10-08 12:07:15  更:2021-10-08 12:07:44 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 2:37:57-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码