【问题标题】:How can I deal with the " ' in os.system cmd command?如何处理 os.system cmd 命令中的“'”?
【发布时间】:2015-05-02 19:58:44
【问题描述】:

我正在使用python os.system调用imagemagick命令为一些图像添加一些文本,代码如下:

os.system("convert -size 2048x2048 xc:transparent -point -fill white -pointsize 75 -draw \"text 50,100 \'thing\'\" C:\\Users\\admin\\Desktop\\test\\output.png"), 但是,它什么也没做。

然后我尝试删除字符串中的斜杠,但也没有任何反应。看来os.system不擅长引号问题。但我认为这些问题应该有一个适当的解决方案。

那么任何人都可以帮我分析这个命令字符串吗?

当然,在命令行中,它运行良好:convert -size 2048x2048 xc:transparent -point -fill white -pointsize 75 -draw "text 50,100 'thing'" C:\\Users\\admin\\Desktop\\test\\output.png

【问题讨论】:

  • 你为什么要转义双引号?只转义单引号os.system('convert -size 2048x2048 xc:transparent -point -fill white -pointsize 75 -draw "text 50,100 \'thing\'" C:\\Users\\admin\\Desktop\\test\\output.png')
  • 该命令是否从命令行工作?
  • @Monodeep,感谢您的帮助,现在可以使用了。
  • @LeuZhe 很高兴它有帮助

标签: python imagemagick


【解决方案1】:

如果您需要创建复杂的字符串,请使用三引号("')和原始字符串前缀 (r),以防止解释转义码。此外,subprocess 应该优先于 os.system 用于运行命令。例如。

import shlex
import subprocess

cmd = r"""convert -size 2048x2048 xc:transparent -point -fill white 
    -pointsize 75 -draw  "text 50,100 'thing'" 
    C:\Users\admin\Desktop\test\output.png"""
retcode = subprocess.call(shlex.split(cmd, posix=False)) 

shlexposix=False 时保留双引号之间(包括双引号)的所有内容。也许这不是你想要的。如果不使用posix=False,则单个参数"text 50,100 'thing'" 将变为单个参数text 50,100 'thing'(没有双引号)。但是,您需要引用文件名以防止将 \ 解释为转义字符。

cmd = r"""convert -size 2048x2048 xc:transparent -point -fill white 
    -pointsize 75 -draw "text 50,100 'thing'" 
    'C:\Users\admin\Desktop\test\output.png'"""
retcode = subprocess.call(shlex.split(cmd))

【讨论】:

  • 嗨,它看起来很有希望!
【解决方案2】:

imagemagick 有一个 Python API。

good reasoning 背后的原因在 API 可用时使用 os.system 执行此类任务。

也就是说,我认为问题在于转义 \'thing\' 中的单引号,所以也许这会起作用:

os.system("convert -size 2048x2048 xc:transparent -point -fill white -pointsize 75 -draw \"text 50,100 'thing'\" C:\\Users\\admin\\Desktop\\test\\output.png")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-25
    • 2012-07-16
    • 1970-01-01
    • 2023-03-16
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多