【问题标题】:Why character '^' is ignored byt Python Popen - how to escape '^' character in Popen Windows?为什么 Python Popen 忽略字符 '^' - 如何在 Popen Windows 中转义 '^' 字符?
【发布时间】:2015-03-07 23:35:33
【问题描述】:

我准备了一些代码来执行这样的命令行:

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

【问题讨论】:

  • 尝试将列表传递给Popen,而不是字符串。这有时会有所帮助。
  • @Kevin 不管看到下面的模块代码列表都会加入。
  • 无关:Popen(cmd).wait()subprocess.call(cmd)

标签: python windows python-2.7 imagemagick subprocess


【解决方案1】:

为什么 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'])

后一个命令使用遵循Parsing C Command-Line Arguments 规则的subprocess.list2cmdline() 将列表转换为命令字符串——它对^ 没有影响。

^ 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。它包括^ 本身。

【讨论】:

  • 如果我正确地遵循这一点,问题实际上与问题中指定的相反 - 在命令行键入命令时会删除 ^,但在使用 @ 时会保留987654339@.
  • @MarkRansom:是的。 ^ 转义命令行中的下一个字符,但如果在没有shell=True 的情况下使用Popen(),则它没有特殊含义。我的猜测是 OP 没有提供实际代码(即使用了 shell=True)或 convert 命令损坏了参数本身。
  • 我被添加了 shell=True tp 删除问题 - 现在我更好地理解了根本原因 - 很好的解释。
  • @eryksun:要明确一点:答案不推荐shell=True。它只是说没有shell=Truecmd.exe 没有解释),^ 并不特殊,即^ 按原样传递给命令。
猜你喜欢
  • 2019-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 2013-04-18
  • 1970-01-01
相关资源
最近更新 更多