V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
? Learn Python the Hard Way
Python Sites
? PyPI - Python Package Index
? http://diveintopython.org/toc/index.html
? Pocoo
值得关注的项目
? PyPy
? Celery
? Jinja2
? Read the Docs
? gevent
? pyenv
? virtualenv
? Stackless Python
? Beautiful Soup
? 结巴中文分词
? Green Unicorn
? Sentry
? Shovel
? Pyflakes
? pytest
Python 编程
? pep8 Checker
Styles
? PEP 8
? Google Python Style Guide
? Code Style from The Hitchhiker's Guide
oldbird
V2EX  ?  Python

多进程处理数据时如何完整打印?

  •  
  •   oldbird · 2021-01-12 11:06:07 +08:00 · 1916 次点击
    这是一个创建于 1217 天前的主题,其中的信息可能已经有所发展或是发生改变。

    腾讯云最新优惠活动来了:云产品限时1折,云服务器低至88元/年 ,点击这里立即抢购:9i0i.cn/qcloud,更有2860元代金券免费领取,付款直接抵现金用,点击这里立即领取:9i0i.cn/qcloudquan

    (福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

    from multiprocessing import Pool

    def do(item):

    	print item
    
    	...... #处理 txt (每个大概 5 分钟)
    

    if name=='main':

    	items=glob.glob('*.txt')
    
    	pool=Pool(5)
    
    	pool.map(do,items)
    
    	pool.close()
    
    	pool.join()
    

    items 为['1111.txt','2222.txt','3333.txt','4444.txt','5555.txt',......'9999.txt']

    运行时会穿插打印,比如 111221.33txt

    是否有办法将每项打印完整?

    8 条回复  ?  2021-02-28 13:49:46 +08:00
    maocat
        1
    maocat  
       2021-01-12 11:06:55 +08:00
    上锁,改同步
    crackhopper
        2
    crackhopper  
       2021-01-12 11:14:19 +08:00
    还可以用 queue,有个线程安全的 queue,用 multiprocessing.Manager,上面带了一个 queue 。
    BrokenVns
        3
    BrokenVns  
       2021-01-12 11:14:23 +08:00
    再启动一个日志进程,通过 socket 把每个进程的日志发送过去,由日志进程汇总打印。
    UN2758
        4
    UN2758  
       2021-01-12 11:56:25 +08:00
    可以用带队列功能的日志,比如 loguru
    VYSE
        5
    VYSE  
       2021-01-12 12:11:58 +08:00
    jones2000
        6
    jones2000  
       2021-01-12 14:18:26 +08:00
    还不如每个进程一个日志文件, 每行日志加时间戳,最后显示的时候读多个文件日志,根据时间戳排序下。 省事
    oldbird
        7
    oldbird  
    OP
       2021-02-28 08:52:23 +08:00
    @jones2000 请问每个进程一个日志该怎么写? 目前只会对每个进程中的每个处理文件一个日志……
    jones2000
        8
    jones2000  
       2021-02-28 13:49:46 +08:00
    @oldbird 我直接用 log4net 插件, 它有统一的写日志的接口.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1069 人在线   最高记录 6547   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 19:06 · PVG 03:06 · LAX 12:06 · JFK 15:06
    Developed with CodeLauncher
    ? Do have faith in what you're doing.


    http://www.vxiaotou.com