質問

I am using Python 2.7.6, i had a problem converting some png files into gif (in order to create an animation)

    os.system("convert -delay 1 -dispose Background +page " + str(output_dir)
      + "/*.png -loop 0 " + str(output_dir) + "/animation.gif")

This was the error that i had

ParamŠtre non valide - 1

役に立ちましたか?

解決

Without enough information to go on, this is only a guess, but…

If output_dir has any spaces or quotes or other special characters, you're doing nothing to escape or quote them, so your command line will look something like this:

convert -delay 1 -dispose Background +page ~/My Pictures/*.png -loop 0 ~/My Pictures/animation.gif

Maybe ~/My is a perfectly valid argument to send for the input, and Pictures/*.png happens to resolve to a whole bunch of additional relative paths that convert is willing to deal with as additional inputs, but then you've got ~/My for the output, which isn't valid since it's the same as the input, and Pictures/animation.gif as some extra argument tacked on the end that convert has no idea what to do with.

You could hack your way around this problem by, say, using repr(output_dir), which will do the appropriate Python-literal quoting, which is often but not always good enough to be used as bash quoting as well… but that's a really bad idea.


A much better way to do this is to let Python do the appropriate quoting for you. As the os.system docs say:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.

With subprocess, you can just pass a list of arguments instead of trying to form them into a valid command line, and not even use the shell—although then you would need to do the globbing yourself instead of letting the shell do it.

While you're at it, it's a lot better to use os.path methods instead of string methods for dealing with paths.

For example:

args = (['convert', '-delay', '1', '-dispose', 'Background', '+page'] +
        glob.glob(os.path.join(output_dir, '*.png')) +
        ['-loop', '0', os.path.join(output_dir, 'animation.gif')])
subprocess.check_call(args)

Or, alternatively, you can still use the shell, but then use shlex.quote to quote each argument for you, as the docs explain.


An even better solution is to use any of the three Python bindings to ImageMagick in the first place, instead of trying to build command lines to drive the ImageMagick command-line tools.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top