How not to quote argument in subprocess?

你。 提交于 2021-02-08 06:19:59

问题


I'm trying to call an ImageMagick command from Python 2.7 using subprocess.call. My problem is that the argument parser in subprocess puts a double quotation mark around every argument, and ImageMagick seems to have a problem with quotes around non-file arguments.

What I'd like is something like this

"imagemagick.exe" "im1.png" "im2.png" -alpha off ( ... ) -composite "im3.png"

So far I couldn't find a way to do it with subprocess, other than manually constructing the string with ugly + " " + elements and calling it with shell=True.

Here is my code:

args = [    imagemagick,
            filename + "_b.bmp",
            filename + "_w.bmp",
            "-alpha off ( -clone 0,1 -compose difference -composite -negate ) ( -clone 0,2 +swap -compose divide -composite ) -delete 0,1 +swap -compose Copy_Opacity -composite",
            filename + ".png" ]   

subprocess.call( args )

Is there any way to call the correct command without double quotes using subprocess?

Update: inserted the full command line. I'd like to keep that part together, not as "alpha", "-off", ... one by one.


回答1:


When calling external programs with subprocess, every argument must be a different element of args. So try:

args = [    imagemagick,
            filename + "_b.bmp",
            filename + "_w.bmp",
            "-alpha", "off", "( ... )", "-composite",
            filename + ".png" ]

I'm not sure what the ( ... ) represents, but if you put unquoted spaces in there on the command line, they should be separate elements in args too.




回答2:


Thanks to Greg's answer, I've come up with this solution. My point is to make the code easy to read in Python. By this I mean that the complicated part should be kept as a string, as it's important to keep it intact (copy-paste into command line / batch files if needed, etc.)

imarg = "-alpha off ( -clone 0,1 -compose difference -composite -negate ) ( -clone 0,2 +swap -compose divide -composite ) -delete 0,1 +swap -compose Copy_Opacity -composite"
args = [ imagemagick, filename + "_b.bmp", filename + "_w.bmp" ] + imarg.split() + [ filename + ".png" ]
subprocess.call( args )

It seems to work fine! Is there any problem what you see with this?



来源:https://stackoverflow.com/questions/11130538/how-not-to-quote-argument-in-subprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!