如何处理 os.system cmd 命令中的 " '?

Leu*_*ady 2 python imagemagick

我正在使用 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

Dun*_*nes 5

如果您需要创建一个复杂的字符串,请使用三重引号("')和原始字符串前缀 ( 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)) 
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)