python - 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)
推荐阅读
- google-apps-script - 我的 Data Studio 连接器 getData() 函数收到 {} 请求
- c# - 绑定只工作一次
- python - 如何在pygame游戏窗口的角落添加健康分数
- python - python 脚本 - service_exe(conn, r'cmd /c 问题
- amazon-web-services - 为什么 AW API 后调用返回内部服务器错误?
- c++ - 在boost python中使用共享指针自动向下转换返回值
- python-3.x - Kivy 屏幕管理器背景颜色
- javascript - React 组件在重新渲染时创建一个新的状态实例,即使状态没有改变
- javascript - 如何切换(开始/停止)ngrx 操作?
- php - 如何在 PHP 中转义单引号内的双引号?