首页 > 解决方案 > Python subprocess ignores backslash in convert command

问题描述

I want to resize multiple images using 'convert'.

This works great from the command line.

However, when I try to achieve the same from within Python3 using subprocess.Popen, the flag '\!' specifying that the aspect ratio of the image should be ignored during the resizing, does not work.

Starting from source I want source and not source

From the command line this works fine using

convert source.png -resize 1230x80\! out_console.png

If I run this command from within Python3 using

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from subprocess import Popen

cmd = [
    'convert',
    'source.png',
    '-resize',
    r'1230x80\!',       # Use '\!' ignoring the aspect ratio
    'out_subprocess.png',
    ]
proc = Popen(cmd)
proc.communicate()

the result is not resized:

source

I tried to escape the backslash character using r'1230x80\!' or '1230x80\\!' without success.

标签: pythonpython-3.xsubprocessimagemagick-convert

解决方案


! needs to be escaped because you're running in a shell. But the command itself doesn't understand \, and Popen doesn't use the shell (unless you use shell=True, but avoid like the plague)

So you're just overdoing this.

Instead, pass arguments without quoting or escaping:

cmd = [
    'convert',
    'source.png',
    '-resize',
    '1230x80!',
    'out_subprocess.png',
    ]

now you have a portable command line that will even work on Windows (well, on windows there's a convert command which doesn't do the same thing at all so you'll have to specify full path of the convert command)


推荐阅读