2015-03-02 31 views
0

我使用蟒蛇使用os.system調用ImageMagick的命令來添加一些文本一些圖像,代碼如下:我該如何應對「'中使用os.system cmd命令

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

我再試着刪除slashs字符串中,也沒有動靜。看來os.system在引號的問題是不好的。但我認爲應該對這些問題的妥善解決辦法。

那麼任何人都可以幫我分析這個命令字符串嗎?

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

+0

你爲什麼要逃避雙引號?只能轉義單引號'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 2015-03-02 13:00:48

+0

命令是否從命令行工作? – 2015-03-02 13:09:13

+0

@Monodeep,感謝您的幫助,它現在可以工作。 – 2015-03-02 15:36:51

回答

0

沒有爲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") 
3

如果你需要創建一個複雜的字符串使用三重引號(無論是"')和防止轉義碼解釋的原始字符串前綴(r)。另外subprocess應優先於os.system運行命令。例如。之間幷包括了雙引號posix=False

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

shlex保留一切。也許這不是你想要的。如果不使用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)) 
+0

嗨,它看起來很有前途! – 2015-03-02 15:37:47