11

I am trying to run a command with subprocess.check_output without using shell=True keyword argument. My command is this:

command --parameter="something with spaces"

With this:

subprocess.check_output(['command', '--parameter="something with spaces"'])

command becomes to this:

command "--parameter=\"something with spaces\""

And with this:

subprocess.check_output(['command', '--parameter=', 'something with spaces'])

command becomes to this(white space after =):

command --parameter= "something with spaces"

Is there a proper way to do that without using shell=True

2 Answers 2

16

Here's what you need to know:

Spaces are used for separating arguments on the shell command line. However, if you are not using shell, you don't need to escape spaces. Spaces can be escaped at least two ways ( that I know of ): With quotes ( either single or double ) and the backslash .

When you pass an array to subprocess.check_output() you are already dividing the command into parameters for the subprocess. Thus, you don't need the quotes around "something with spaces". That is, you don't need to escape the spaces. Rather, the quotes are being taken quite literally as quotes as you have shown with your result snippet:

command "--parameter=\"something with spaces\""

By now I hope you have guessed what the right answer is. Spoiler ahead:

subprocess.check_output(['command', '--parameter=something with spaces'])
Sign up to request clarification or add additional context in comments.

1 Comment

I thought command "--parameter=something with spaces" wouldn't work on shell because of quoting --parameter too, but it does! Thanks
1

Adding to @Mark's answer, I specifically needed quotes to be passed to the program as well as quotes to surround the parameter. Basically this was what I needed:

make PAYOFF="\"{{0,1,-1},{-1,0,1},{1,-1,0}}\""

Python doesn't add the extra set of quotes to the very left and very right, so adding a space in front of the equals sign did the trick.

Calling the list2cmdline functions as follows:

subprocess.list2cmdline(['make', 'PAYOFF ="{{0,1,-1},{-1,0,1},{1,-1,0}}"'])

would produce this result:

make "PAYOFF =\"{{0,1,-1},{-1,0,1},{1,-1,0}}\""

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.