【问题标题】:Why does subprocess.Popen not properly recognize command?为什么 subprocess.Popen 不能正确识别命令?
【发布时间】:2017-11-01 06:47:27
【问题描述】:

我正在尝试执行“*.py”脚本(通过“python *.py”在 CMD 的控制台中),其中包含以下代码(“convert”是 ImageMagick 的命令):

from subprocess import Popen
fp1 = 'convert'+' '+'Pictures\1110.6437v3.pdf[7]'+' '+'-thumbnail'+' '+'x156'+' '+'thumb.png'
print("fp1=", fp1)
pp = Popen(fp1)

我在控制台窗口中得到以下输出和错误:

fp1= 转换图片\1110.6437v3.pdf[7] -thumbnail x156 拇指.png

无效参数 - -thumbnail

这很奇怪,因为如果我在 CMD 中输入以下命令:

转换 1110.6437v3.pdf[7] -thumbnail x156 thumb.png

没关系。

【问题讨论】:

  • 感谢您对编辑的建议。为清楚起见,我在问题中删除了“C:\Users***\”。但问题依然存在。

标签: windows python-3.x cmd subprocess imagemagick-convert


【解决方案1】:

我不是子进程或 Python 方面的专家。我刚刚涉足了一点。我认为您的 fp1 语法可能有误。它不应该是带逗号的方括号(至少在 Python 3.6 中)。见https://docs.python.org/3/library/subprocess.html

但以下对我来说可以运行 ImageMagick 命令以在 Mac OSX 上的 Python 3.6 中创建字母“P”的图像。

import subprocess

cmd = '/usr/local/bin/convert -size 30x40 xc:white -fill white -fill black -font Arial -pointsize 40 -gravity South -draw "text 0,0 \'P\'" /Users/fred/desktop/draw_text2.gif'

subprocess.call(cmd, shell=True)


使用 shell=True 可以不必解析命令的每一部分。例如使用 shell=False,我必须这样做

import subprocess

cmd = ['/usr/local/bin/convert','-size','30x40','xc:white','-fill','white','-fill','black','-font','Arial','-pointsize','40','-gravity','South','-draw',"text 0,0 'P'",'/Users/fred/desktop/draw_text1.gif']

subprocess.call(cmd, shell=False)

【讨论】:

  • Windows CreateProcess 使用命令行字符串而不是 argv 数组。 args 列表必须通过subprocess.list2cmdline 转换回字符串。但在 Windows 上使用 args 列表可能有充分的理由。它有助于编写跨平台代码。此外,它使用了 Windows 程序常用的 VC++ 引用规则,这可能比手动编写命令行更容易、更可靠。
  • 当我在 'pp = Popen(fp1)' 中添加 'shell=True' 作为 'pp = Popen(fp1, shell=True)' 时,错误消失了,我得到了我的结果想要(尽管有一些警告)。谢谢,@fmw42 和 @eryksun。
猜你喜欢
  • 1970-01-01
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 2015-04-21
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
  • 1970-01-01
相关资源
最近更新 更多