I'm trying to run bash code via python. Normal statements (netstat, for example) work. If functions like the one below, however, don't. What should I change in order to run the following code correctly?
Thanks in advance
>>> import os
>>> import subprocess
>>> _c = 'if [ "$a" == "test" ]; then echo $a; fi'
>>> print(subprocess.Popen(_c, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8'))
/bin/sh: 1: [: anto: unexpected operator
The command you are trying to run in the subprocess is following the
bash shell syntax, where the string equality test is performed via
==. Now, on Unix with shell=True, the shell defaults to
/bin/sh where instead the equality test is performed via a simple
=. The two options you have here are:
shsyntax in your script
As for option (1), replace
_c as follows and it should work fine:
import os, subprocess m_env = os.environ m_env['a'] = "test" _c = 'if [ "$a" = "test" ]; then echo $a; fi' print(subprocess.Popen(_c, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8'))
That prints out "test".