python - 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 文件。
解决方案
使用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))
推荐阅读
- node.js - nodejs 文件更改甚至没有反映 nodemon 和主管
- reactjs - React,Material-UI:如何使用 typescript 组合具有自定义道具的功能组件
- angular - angular fullcalendar:从日历中打开自定义弹出窗口
- javascript - onclick 时从父控制器更改的按钮组件文本不起作用 - AngularJS 1.7
- c# - Search a comma separated value using Entity framework
- excel - Scenario Builder using VBA
- batch-file - 用于国际象棋引擎的 Windows 中的 Bat 文件
- python - 无法使用 Requests 和 BeautifulSoup 获得正确的值
- mysql - MySQL if updated older than 5 minutes and some other where clause
- xampp - MySQL 意外关闭。这可能是由于端口被阻塞,缺少对 phpmyadmin 的依赖