pidgey pidgey - 1 month ago 13
Python Question

if statement in subprocess.Popen

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
>>>
>>> os.setenv['a']='test'
>>> _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

sal sal
Answer

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:

  1. follow sh syntax in your script
  2. explicitly call '/bin/bash' as the executable to be run

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".

Comments