首页 > 解决方案 > Python 脚本违反了命令行字符限制

问题描述

我正在使用 Python 脚本将不同文件夹中的许多图像批量转换为单个 pdf(使用https://pypi.org/project/img2pdf/):

import os
import subprocess
import img2pdf 
from shutil import copyfile

def main():
    folders = [name for name in os.listdir(".") if os.path.isdir(name)] 
    for f in folders:
        files = [f for f in os.listdir(f)] 
        p = ""
        for ffile in files:
            p += f+'\\'  + ffile + " "                
        os.system("py -m img2pdf *.pn* " + p + " --output " + f + "\combined.pdf")
    
        
if __name__ == '__main__':
    main()

然而,尽管在 Windows 10 上通过 Powershell 运行命令,并且尽管使用了非常短的文件名,但当图像数量非常多(例如超过 600 个左右)时,Powershell 给我错误“命令行太长”并且它不创建pdf。我知道有一个命令行字符串限制(https://docs.microsoft.com/en-us/troubleshoot/windows-client/shell-experience/command-line-string-limitation),但我也知道powershell 这个限制更高(Powershell to Avoid cmd 8191 character limit),我不知道如何修复脚本。我想问你是否可以帮助我修复脚本以避免违反字符限制。谢谢

PS:我将脚本插入到包含图像文件夹的父文件夹中后使用该脚本;然后在每个子文件夹中创建输出 pdf 文件。

标签: pythonpowershellcommand-linelimitimg2pdf

解决方案


使用img2pdf库,您可以使用此脚本:

import img2pdf
import os

for r, _, f in os.walk("."):
    imgs = []
    for fname in f:
        if fname.endswith(".jpg") or fname.endswith(".png"):
            imgs.append(os.path.join(r, fname))
    if len(imgs) > 0:
        with open(r+"\output.pdf","wb") as f:
            f.write(img2pdf.convert(imgs))

推荐阅读