簡體   English   中英

如何處理os.system cmd命令中的“”?

[英]How can I deal with the " ' in os.system cmd command?

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

如果您需要創建復雜的字符串,請使用三引號( "' )和原始字符串前綴( r ),以防止轉義碼的解釋,此外,對於運行命令, subprocessos.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)) 

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

有一個用於imagemagick的Python API。

足夠的理由說明為什么在有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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM