【问题标题】:Porting 'sh 1.11'-based code to Windows将基于“sh 1.11”的代码移植到 Windows
【发布时间】:2015-04-21 12:53:48
【问题描述】:

所有迹象似乎都表明我的脚本可以在 Linux 环境中完全运行,据我所知,唯一阻止它在 Windows 中运行的就是我使用了 sh,这非常简单:

from sh import convert

convert(inputfile, '-resize', r, '-quality', q, '-strip', outputfile)

这转换为 bash 行:

convert image.jpg -resize 350x350 -quality 80 -strip ./small/export.jpg

其中rq 变量是任何给定的分辨率或质量。


在 Windows 中运行它当然会引发错误,因为“sh”在 Windows 中完全不起作用:(我尝试用已弃用的 pbs 替换“sh”,但没有任何运气。这就是我的到目前为止:

import pbs

pbs.convert('-resize', r, '-quality', q, '-strip', inputfile, outputfile)

引发的错误是:

  File "C:\Python27\lib\site-packages\pbs.py", line 265, in _create
    if not path: raise CommandNotFound(program)
pbs.CommandNotFound: convert

问题:

如何在 Windows 环境中从我的脚本中成功传递这些 ImageMagick 命令?

【问题讨论】:

  • 为什么不使用 subprocess 和 popen 或调用?
  • @IronManMark20:我试图弄清楚如何使用它们。 subprocess 似乎是正确的方向,但它不像 sh 那样对新手友好。

标签: python subprocess porting imagemagick-convert


【解决方案1】:

Kevin Brotckeanswer 之后,这是我们使用的 hack:

try:
    import sh
except ImportError:
    # fallback: emulate the sh API with pbs
    import pbs
    class Sh(object):
        def __getattr__(self, attr):
            return pbs.Command(attr)
    sh = Sh()

【讨论】:

  • 谢谢!同样在__getattr__ 中添加if hasattr(self, attr): return getattr(self, attr) 保留通过sh 对Command 类的访问权
【解决方案2】:

pbs.CommandNotFound 错误信息是因为 pbs 没有convert 方法。相反,您需要使用Command 方法:

import pbs
convert = pbs.Command('convert')

现在你可以像sh一样使用它了:

convert(inputfile, '-resize', r, '-quality', q, '-strip', outputfile)

【讨论】:

    【解决方案3】:

    子流程是您最好的选择。虽然,正如您所说,它不是最容易学习的,但它确实很有用。我会看看this indepth tutorial。当然,也请阅读the docs

    至于你的具体问题,sh 比 pbs 存在的时间更长,所以它几乎肯定有更多的功能。查看源代码 (pbs.py),我发现没有名为 convert() 的函数。此外,您将调用的参数从sh 更改为pbs(您没有输入inputfile)。最后,来自 git repo 的 sh.py 中没有名为 convert() 的函数,所以我怀疑您将它与从其他东西转换混淆了。

    除此之外,您应该能够结合使用pbssubprocess

    【讨论】:

    • 我认为您错过了pbssh 的要点。它们支持动态导入,您可以直接执行from sh import asdfasdfgqer,它会在您的$PATH 中查找名为asdfasdfgqer 的程序。
    【解决方案4】:

    您可以use stdlib's subprocess module,在 Windows 上运行命令:

    #!/usr/bin/env python
    from subprocess import check_call
    
    check_call(r'c:\path\to\ImageMagick\convert.exe image.jpg -resize 350x350 -quality 80 -strip small\export.jpg')
    

    提供带有文件扩展名的完整路径很重要,否则为different convert command may be chosen

    如果convert 以非零状态退出,check_call() 将引发异常。您可以使用 subprocess.call() 并手动检查状态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多