When using subprocess.Popen, we have to write
with subprocess.Popen(['ls', '-l', '-a'], stdout=subprocess.PIPE) as proc:
print(proc.stdout.read())
instead of
with subprocess.Popen(['ls', '-l -a'], stdout=subprocess.PIPE) as proc:
print(proc.stdout.read())
Why? What ls will get in the second case? Thank you.
In the second case
-l -aas a single string will be the first argument tols, which it won't know what to do with, or at least won't do what you want. In the first case-lis the first argument and-ais the second argument.If you want to build a string that has the complete command you can use the
shell=Trueflag to Popen, but then your command would be"ls -l -a"not['ls', '-l -a']With
Popeneach argument in the list is an argument passed to the command being executed, it's not a string passed to the shell to be interpreted, unless you ask for it to be passed to the shell to be interpreted.