Why character '^' is ignored byt Python Po

2019-01-08 00:35发布

问题:

I prepared some code to execute such command line:

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"

This works fine from command line (same command as above) but 352x352^ is 352x352^ not 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"

If run this code from python - character '^' is ignored and resized image has size as '%sx%s' is passed not %sx%s^ - Why Python cuts '^' character and how to avoid it?:

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

回答1:

Why Python cuts '^' character and how to avoid it?

Python does not cut ^ character. Popen() passes the string (resize_command) to CreateProcess() Windows API call as is.

It is easy to test:

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

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

The latter command uses subprocess.list2cmdline() that follows Parsing C Command-Line Arguments rules to convert the list into the command string -- it has not effect on ^.

^ 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. It includes ^ itself.