I am confused about invoking bash from python code.
I wrote a small script that shows strange behaviors when invoking bash from python :
import subprocess
def check_output ( command,**w ):
print( '\n>>> %s'%command )
try :
return subprocess.check_output( command,**w ).decode()
except Exception as e :
return str( e )
print( check_output( ['ls','-l']))
print( check_output( ['ls','-l',';','ls','-a']))
print( check_output( 'ls -l' ))
print( check_output( 'ls -l ; ls -a' ))
print( check_output( ['echo','99'],shell=1))
print( check_output( ['echo','11',';','echo','22'],shell=1))
print( check_output( 'echo 33 ; echo 44',shell=1 ))
And the output:
>>> ['ls', '-l']
total 124
-rwxrwxrwx 1 root root 59 Mar 22 09:57 main.py
-rwxrwxrwx 1 root root 3885 Mar 17 17:30 README.md
drwxrwxrwx 0 root root 4096 Mar 22 10:33 src
-rwxrwxrwx 1 root root 36 Mar 22 09:57 sub.c
drwxrwxrwx 0 root root 4096 Mar 22 10:33 test
>>> ['ls', '-l', ';', 'ls', '-a']
ls: cannot access ';': No such file or directory
ls: cannot access 'ls': No such file or directory
Command '['ls', '-l', ';', 'ls', '-a']' returned non-zero exit status 2.
>>> ls -l
[Errno 2] No such file or directory: 'ls -l': 'ls -l'
>>> ls -l ; ls -a
[Errno 2] No such file or directory: 'ls -l ; ls -a': 'ls -l ; ls -a'
>>> ['echo', '99']
>>> ['echo', '11', ';', 'echo', '22']
>>> echo 33 ; echo 44
33
44
The first and last commands are as I expected, but the others seems strange to me.
The multiple commands separator ; seems to act differently depending on parameter shell. And also the concatenated commands...
By the way I get the same results with python 2 and 3 (under kali linux).