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
JCZ2MkKb5S8ZX9pq
V2EX  ›  Python

Python 内存问题求教

  •  
  •   JCZ2MkKb5S8ZX9pq · 2020-10-17 21:26:43 +08:00 · 1785 次点击
    这是一个创建于 1259 天前的主题,其中的信息可能已经有所发展或是发生改变。
    # 伪代码
    from psd_tools import PSDImage
    
    def main():
        for file in file_list:
            save_jpg(file)
            
    def save_jpg(file):
        img = PSDImage.open(file).composite()
        img.save(output_name)
    
    • 想要批量给 psd 导出缩略图( PS actions 我会的,我只是简化说明,其实要做不少其他操作,所以想用 python )。
    • 现在的问题是,如果每次只操作一个文件(做一次save_jpg),运行正常。
    • 但如果把同一个 psd 复制多份,然后运行 main 的话,内存就会出错。症状是第一个文件正常开启,第二个开始内存就不足了。
    • 搞不清楚这个内存管理是咋回事儿。试了在save_jpgdel img啥的也没什么用,我感觉save_jpg运行完一次应该就释放内存了。不知道是不是依赖库有问题,但有些 psd 直接用 PIL.Image 打不开,才用到的这个第三方库。

    • 刚才又观察了一下,其实运行时内存用量并不高,那可能还是这个库的问题?
    5 条回复    2020-10-18 09:56:39 +08:00
    sss495088732
        1
    sss495088732  
       2020-10-17 22:54:22 +08:00
    看源码有没有释放句柄
    xchaoinfo
        2
    xchaoinfo  
       2020-10-17 23:44:43 +08:00 via Android
    with PSDImage.open
    ipwx
        3
    ipwx  
       2020-10-17 23:45:57 +08:00
    1. 请及时关闭不需要的东西。
    2. 32 位程序只能用 2GB 用户态内存。请确信你用的不是 32 位 python 。
    laike9m
        4
    laike9m  
       2020-10-18 00:07:47 +08:00
    你需要的不是猜测,而是 profiling,推荐几个库吧:
    https://github.com/pythonprofilers/memory_profiler
    https://mg.pov.lt/objgraph/
    nonduality
        5
    nonduality  
       2020-10-18 09:56:39 +08:00
    假如你尝试这么写呢?

    ```python
    def save_jpg(file):
    fd = PSDImage.open(file)
    fd.composite().save(output_name)
    fd.close()
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2482 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 911ms · UTC 15:45 · PVG 23:45 · LAX 08:45 · JFK 11:45
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.