python - Advantage of list over string in subprocess methods -


what advantages of using list on string in subprocess methods? ones understand far:

  • security if input comes external sources
  • portability on different operating systems

are there others?

in particular case, i'm using subprocess library run tests on software. input not come external source. tests run on linux. therefore, see no benefit of lists on strings.

on posix, list , string arguments have different meaning , used in different contexts.

you use string argument , shell=true run shell command e.g.:

from subprocess import check_output  output = check_output("dmesg | grep hda", shell=true) 

a list argument used run command without shell e.g.:

from subprocess import check_call  check_call(["ls", "-l"]) 

one exception call("ls") equivalent call(["ls"]) (a command no arguments).

you should use list argument shell=false (default) except in cases when need shell string argument used.

it error use list argument , shell=true (the arguments interpreted arguments shell instead of command in case). don't use it.

if question: advantages of shell=false , hence list argument on string argument:

  • you don't need escape arguments, no shell interpolation such word splitting, parameter expansion, command substitution occurs: see
    • support arguments spaces
    • support arguments special characters such quotes, dollar sign, etc
  • it clear arguments boundaries are. explicitely separated.
  • it clear program executed: first item in list
  • an argument populated untrusted source won't able execute arbitrary commands
  • why run superfluous shell process unless need

sometimes, might more convenient/readable specify argument string in source code; shlex.split() used convert list:

import shlex subprocess import check_call  cmd = shlex.split('/bin/vikings -input eggs.txt -output "spam spam.txt" '                   '''-cmd "echo '$money'"''') check_call(cmd) 

see the docs.


on windows, arguments interpreted differently. native format string , passed list converted string using subprocess.list2cmdline() function may not work windows programs. shell=true necessary run builtin shell commands.

if list2cmdline() creates correct command line executable (different programs may use different rules interpreting command line) list argument used portability , avoid escaping separate arguments manually.


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -