2015-01-09 42 views
2

我製備一些代碼來執行這樣的命令行:爲什麼字符'^'忽略byt Python Popen - 如何在Popen Windows中轉義'^'字符?

c:\cygwin\bin\convert "c:\root\dropbox\www\tiff\photos\architecture\calendar-bwl-projekt\bwl01.tif" -thumbnail 352x352^ -format jpg -filter Catrom -unsharp 0x1 "c:\root\dropbox\www\tiff\thumbnails\architecture\calendar-bwl-projekt\thumbnail\bwl01.jpg" 

這工作從命令行(相同的命令如上述),但是352x352細^是352x352 ^不352x352:

c:\cygwin\bin\convert "c:\root\dropbox\www\tiff\photos\architecture\calendar-bwl-projekt\bwl01.tif" -thumbnail 352x352^ -format jpg -filter Catrom -unsharp 0x1 "c:\root\dropbox\www\tiff\thumbnails\architecture\calendar-bwl-projekt\thumbnail\bwl01.jpg" 

如果運行該python中的代碼 - 字符'^'被忽略,並且調整大小的圖像的大小爲'%sx%s'通過而不是%sx%s^- 爲什麼Python會剪切'^'字符以及如何避免它?

def resize_image_to_jpg(input_file, output_file, size): 
    resize_command = 'c:\\cygwin\\bin\\convert "%s" -thumbnail %sx%s^ -format jpg -filter Catrom -unsharp 0x1 "%s"' \ 
        % (input_file, size, size, output_file) 
    print resize_command 
    resize = subprocess.Popen(resize_command) 
    resize.wait() 
+0

嘗試將列表傳遞給'Popen'而不是字符串。有時這有助於。 – Kevin

+0

@Kevin無論看到模塊代碼下面的列表都會加入。 – Chameleon

+0

無關:'Popen(cmd).wait()'是'subprocess.call(cmd)'的意思。 – jfs

回答

3

爲什麼Python的削減 '^' 字符,以及如何避免呢?

Python不會削減^字符。 Popen()按原樣將字符串(resize_command)傳遞給CreateProcess() Windows API調用。

這是很容易測試:

#!/usr/bin/env python 
import sys 
import subprocess 

subprocess.check_call([sys.executable, '-c', 'import sys; print(sys.argv)'] + 
         ['^', '<-- see, it is still here']) 

後者命令使用subprocess.list2cmdline()遵循Parsing C Command-Line Arguments規則列表轉換成命令字符串 - 它不是在^影響。

^ is not special for CreateProcess(). ^ is special if you use shell=True (when cmd.exe is run)

if and only if the command line produced will be interpreted by cmd, prefix each shell metacharacter (or each character) with a ^ character。它包括^本身。

+0

如果我正確地執行此操作,問題實際上與問題中指定的內容相反 - 在命令行鍵入命令時會放棄「^」,但在使用「Popen」時會保留該命令。 –

+1

@MarkRansom:是的。 '^'在命令行中轉義下一個字符,但如果'Popen()'沒有使用'shell = True',則它沒有特殊含義。我的猜測要麼OP沒有提供實際的代碼(即使用'shell = True'),要麼'convert'命令會破壞參數本身。 – jfs

+0

我被加入shell = True tp刪除問題 - 現在我明白根本原因更好 - 非常好的解釋。 – Chameleon