if statement in subprocess.Popen
<p>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</p>

<pre><code>&gt;&gt;&gt; import os
&gt;&gt;&gt; import subprocess
&gt;&gt;&gt; 
&gt;&gt;&gt; os.setenv['a']='test'
&gt;&gt;&gt; _c = 'if [ "$a" == "test" ]; then echo $a; fi'
&gt;&gt;&gt; print(subprocess.Popen(_c, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8'))
/bin/sh: 1: [: anto: unexpected operator
</code></pre>

<p>The command you are trying to run in the subprocess is following the <code>bash</code> shell syntax, where the string equality test is performed via <code>==</code>. Now, on Unix with shell=True, the shell defaults to <code>/bin/sh</code> where instead the equality test is performed via a simple <code>=</code>. The two options you have here are:</p>

<ol>
<li>follow <code>sh</code> syntax in your script</li>
<li>explicitly call '/bin/bash' as the executable to be run by adding <code>executable='/bin/bash'</code> to the Popen</li>
</ol>

<p>As for option (1), replace <code>_c</code> as follows and it should work fine:</p>

<pre><code>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'))
</code></pre>

<p>That prints out "test".</p>

python bash if-statement subprocess