Search code examples
pythonwindowspython-2.7imagemagicksubprocess

'^' is ignored by Python - how to escape '^' character in Popen Windows?


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, the ^ character is ignored and the resized image has size as if '%sx%s' was passed instead of %sx%s^

Why does Python cut out the ^ character and how can I 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()

Solution

  • 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.