如何从Python后台运行ImageMagick

3 投票
1 回答
3323 浏览
提问于 2025-04-17 12:51

如何在Python中使用imagemagick,而不打开新的命令行窗口,也不失去焦点呢?

这个循环展示了问题;在处理图像时,系统变得无法使用,因为每次调用系统命令时都会失去焦点:

for i in range(0,100,1):
    image = 'convert -background '+'black'+' -fill '+'white'+' -font '+'arial'+' -size '+'50'+'x50'+' -encoding utf8'+' -gravity center caption'+':'+'"just stole your focus"'+' '+'C:/'+'testFile.png'
    os.system(image)

使用'开始 /min'或'/b'只会快速最小化窗口,所以你还是会失去焦点。而且出于某种原因,如果我把这些放在'image'之前,我就得不到输出文件。

有没有什么方法可以使用os.systemos.spawnvsubprocess.Popen或者其他系统命令在后台调用imagemagick呢?

我读过关于PythonMagickWand的内容,但只找到了在nix系统上的安装说明:ImageMagick的MagickWand API的Python绑定

我可以在Windows上安装/编译这些绑定吗?如果可以,怎么做呢?

编辑:MRAB的解决方案:

import os
import subprocess

# Start all the processes.
processes = []
# Define directories
convertDir = 'C:/Program Files/ImageMagick-6.7.5-Q16/convert.exe'
outputDir = 'C:/test/'
outputFileName = 'testFile_look_ma_no_windows_'
if not os.path.exists(outputDir):
    os.makedirs(outputDir)

for i in range(100):
    outputDirFile = outputDir+outputFileName+str(i)+'.png'
    image = convertDir+' '+'-background'+' '+'blue'+' '+'-fill'+' '+'white'+' '+'-font'+' '+'arial,'+' '+'-size '+' '+'50x50'+' '+'-encoding'+' '+'utf8'+' '+'-gravity'+' '+'center'+' '+'caption:"did not steal your focus"'+' '+outputDirFile
    #CREATE_NO_WINDOW Flag: 0x08000000
    p = subprocess.Popen(image, creationflags=0x08000000)
    processes.append(p)

# Wait for all the processes to finish.
# Some may finish faster, so the files are out of order before all are done;
# if you need the files immediately, put p.wait after p = subprocess.Popen
# and comment out lines 5,18,24 and 25
for p in processes:
    p.wait()

print 'Done, created ',str(i+1),' images in ',outputDir

1 个回答

3

使用subprocesses.Popen是推荐的做法:

# Start all the processes.
processes = []
for i in range(100):
    p = subprocess.Popen(['convert', '-background', 'black', '-fill', 'white', '-font', 'arial', '-size', '50x50', '-encoding', 'utf8', '-gravity', 'center', 'caption:"just stole your focus"', 'C:/testFile.png'])
    processes.append(p)

# Wait for all the processes to finish.
for p in processes:
    p.wait()

撰写回答