简体   繁体   中英

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来源I want来源and not来源

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:

来源

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

! 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)

In addition to accepted answer : The problem essentially is:

Translate a shell command into a non-shell command.

There is a library solving this task.

import shlex
shlex.split('convert source.png -resize 1230x80\! out_console.png')

gives

['convert', 'source.png', '-resize', '1230x80!', 'out_console.png']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM