Blog

Executing Shell Script From Python

Posted by:

Executing Shell Script From Python

Python LogoIn *nix systems administration, the language used almost all the time is Bash/sh. Lately, I faced the idea of moving lots of shell scripts to python. As a step by step procedure, I have to call/run them from a python script. Afterwards, I can think of translating the Bash scripts to python, and then by time a full migration to python scripts.

For that, I searched python on the web for calling commands and I found nice resources, but most of the available resource do not support returning the Bash output. Most of them are returning the exit value ( 0 , 1, 2 ) of the executed shell command.

Except for Popen + PIPE. Here, I faced as well the bash pipes ( | ) in commands and redirections ( < ) & ( > ). So, I thought of putting the passed command in a temporary file.sh, then execute that file.

The function I came up with was exactly like that :



def sh(command,BASH='/bin/bash'):
    """
    Executes a bash command
    @param command: The bash command to execute
    @param BASH: The path to the executable bash
    @return: The console output for the executed command.
    """
    # Creating the temporary file, holding the command
    file = open('./.code.sh','w')
    file.write("#!%s\n%s"%(BASH,command))
    file.flush()
    file.close()
    # Changing file access modifiers to be executable
    os.system('chmod +x ./.code.sh')
    # executing the temporary file.sh
    p1 = Popen(['./.code.sh'], stdout=PIPE)
    # Getting the output and returning it back
    return p1.communicate()[0]

Soon, I will try to improve it, Wish me Luck.

Hope you find that useful.

0