将基于'sh 1.11'的代码移植到Windows

SCK*_*SCK 3 python porting subprocess imagemagick-convert

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

from sh import convert

convert(inputfile, '-resize', r, '-quality', q, '-strip', outputfile)
Run Code Online (Sandbox Code Playgroud)

这转换为bash行:

convert image.jpg -resize 350x350 -quality 80 -strip ./small/export.jpg
Run Code Online (Sandbox Code Playgroud)

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


在Windows中运行它当然会引发错误,因为'sh'在Windows中完全不起作用:(我尝试用不推荐的pbs替换'sh' ,但是没有运气.这是我到目前为止所得到的:

import pbs

pbs.convert('-resize', r, '-quality', q, '-strip', inputfile, outputfile)
Run Code Online (Sandbox Code Playgroud)

引发的错误是:

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

题:

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

Che*_*evy 8

按照Kevin Brotcke回答,这就是我们采用的黑客行为:

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()
Run Code Online (Sandbox Code Playgroud)