How to force os.system() to use bash instead of shell
Asked Answered
M

5

9

I've tried what's told in How to force /bin/bash interpreter for oneliners

By doing

os.system('GREPDB="my command"')
os.system('/bin/bash -c \'$GREPDB\'')

However no luck, unfortunately I need to run this command with bash and subp isn't an option in this environment, I'm limited to python 2.4. Any suggestions to get me in the right direction?

Mesothorax answered 17/2, 2014 at 6:17 Comment(4)
Why the subprocess module is not an option? It is supported in Python 2.4.Vassaux
pretty sure it is in 2.4.6, however this is 2.4.3Mesothorax
What about one of the various exec* functions?Trimeter
Putting a shell command in a shell variable is almost always completely the wrong thing to do.Fourchette
V
15

Both commands are executed in different subshells.

Setting variables in the first system call does not affect the second system call.

You need to put two command in one string (combining them with ;).

>>> import os
>>> os.system('GREPDB="echo 123"; /bin/bash -c "$GREPDB"')
123
0

NOTE You need to use "$GREPDB" instead of '$GREPDBS'. Otherwise it is interpreted literally instead of being expanded.

If you can use subprocess:

>>> import subprocess
>>> subprocess.call('/bin/bash -c "$GREPDB"', shell=True,
...                 env={'GREPDB': 'echo 123'})
123
0
Vassaux answered 17/2, 2014 at 6:23 Comment(2)
unfortunately this is still giving me shell errors :-(Mesothorax
@0n35, Could you post the traceback ?Vassaux
A
8

The solution below still initially invokes a shell, but it switches to bash for the command you are trying to execute:

os.system('/bin/bash -c "echo hello world"')
Allergen answered 24/9, 2015 at 19:6 Comment(0)
W
2

I use this:

subprocess.call(["bash","-c",cmd])

//OK, ignore this because I have not notice subprocess not considered.

Whose answered 8/1, 2016 at 7:9 Comment(2)
Please explain a little more. How does it work? Why is it a workaround?Chthonian
@Chthonian actually it is a workaround to fix my issue in windows msysgit environment.Whose
C
1
subprocess.Popen(cmd, shell=True, executable='/bin/bash')
Chuddar answered 13/9, 2018 at 8:39 Comment(1)
Popen merely starts a process; you should manage the resulting object yourself. Of course, you can just use subprocess.run() instead, which does all of this plumbing for you.Fourchette
P
0

I searched this command for some days and found really working code:

import subprocess

def bash_command(cmd):
    subprocess.Popen(['/bin/bash', '-c', cmd])

code="abcde"
// you can use echo options such as -e
bash_command('echo -ne "'+code+'"')

Output:

abcde
Placentation answered 21/3, 2017 at 1:18 Comment(1)
echo in particular isn't a very good example; you should prefer printf. Though I suppose this would work if your specific question was "how can I use Bash's built-in echo from Python?"Fourchette

© 2022 - 2024 — McMap. All rights reserved.