2015-01-09 43 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