Skip to content Skip to sidebar Skip to footer

Running A Command W/ Quotes In Parameters Works With Commands.getoutput() But Not Subprocess Module

I'm creating a python program that calls a number of other programs and scripts (on Unix(SUNos) + Linux). I'm using subprocess everywhere except for 1 script. The script for which

Solution 1:

You're using syntactic quotes in the commands.getoutput() case, and literal quotes in the subprocess.check_output() case. Without shell=True (which you shouldn't use), there's no shell to parse quotes as syntax, so there's no such thing as a syntactic quote, other than the quotes that are syntax to Python itself.

So, just take out the "s that you injected into your arguments:

# this contains quotes that are syntactic to Python only, and no literal quotes
perl_cmd = [
  '<executable perl-script>',
  '-rt', 'users',
  '-eq', 'name', '<user_name>',
  '-fs', ':',
  '-fld', 'fullname', 'email' ]

To explain a bit more detail --

When you pass "name" to a shell as part of a command, the quotes are consumed by the shell itself during its parsing process, not passed to the command as an argument. Thus, when you run sh -c 'echo "hello"', this passes the exact same argument to echo as sh -c 'echo hello'; the echo command can't even tell the difference between the two invocations!

When you pass '"hello"' as an argument to subprocess.Popen(), by contrast, the outer quotes are consumed by Python, and the inner quotes are passed as literal to the inner command. That makes it equivalent to sh -c 'echo "\"hello\""' (which likewise passes literal quotes through to echo), not sh -c 'echo "hello"' (which does not).


Post a Comment for "Running A Command W/ Quotes In Parameters Works With Commands.getoutput() But Not Subprocess Module"