如何通过Python Subprocess捕获2PDF转换的进度信息
无法捕获2PDF命令行工具的实时进度输出
使用Python subprocess调用fcoder 2PDF命令行工具时,成功捕获了大部分输出内容,但无法获取到显示转换进度的实时更新行信息,需解决该标准输出捕获问题。
现有调用代码
import subprocess # Define the command to run command = [r"C:\Program Files (x86)\2PDF\2PDF.exe","-src", r"C:\Users\Rajkumar\Desktop\a\a2.docx" ,"-dst", r"C:\Users\Rajkumar\Desktop" ,"-options", "mswildc:no" ,"-pdf", "ocr:yes", "ocr_lang:English"] # Use subprocess to run the command and capture the output process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) # Read and print the output while the process is running while True: output = process.stdout.readline() if output == '' and process.poll() is not None: break if output: print(output.strip())
当前捕获到的输出
2PDF, Version 2.0, (c) fCoder SIA 2022 --------------------------------------------------------------- Loading files list, please wait... 1 of 1. "C:\Users\Rajkumar\Desktop\a\a2.docx" -> Pdf ........... Ok All files converted successfully
期望捕获的进度信息
需要捕获的是实时更新的单行进度内容(类似通过回车符\r刷新的"Processing page X of Y"类进度行),这类进度信息目前未被现有代码捕获。
已验证的Python脚本进度捕获方案
已实现捕获Python子进程的单行刷新进度,具体代码如下:
demo7.py(模拟进度输出的子进程)
import time import sys num=1 for i in range(11): text="#"*i+"."*(10-i) print(f"[{text}] {i*10}%",end="\r") time.sleep(0.5)
demo8.py(捕获进度的父进程)
import subprocess,os command=["python",r"E:\PythonDIR\PdfUtil\demo7.py"] # Set PYTHONUNBUFFERED environment variable env = os.environ.copy() env['PYTHONUNBUFFERED'] = '1' # Run demo7.py using subprocess with line buffering process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, env=env) # Continuously read and print the live output while True: output=process.stdout.readline() if output == '' and process.poll() is not None: break print(output ,end='')
该方案能正常捕获Python子进程的实时刷新进度,但针对2PDF这类外部exe无效,希望通过Windows核心API(如ctypes模块)解决该问题。
内容的提问来源于stack exchange,提问作者Raj1234
相关产品推荐
相关产品推荐

