Reputation: 245
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
Upvotes: 0
Views: 2595
Reputation: 3593
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:
sh
syntax in your scriptexecutable='/bin/bash'
to the PopenAs 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".
Upvotes: 2