Running a command w/ quotes in parameters works with commands.getoutput() but not subprocess module

后端 未结 1 2038
闹比i
闹比i 2021-01-29 05:01

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 scri

相关标签:
1条回答
  • 2021-01-29 05:15

    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).

    0 讨论(0)
提交回复
热议问题