Python - evaluate shell command before executing it

Viewed 44

I have a Python function that I made with the subprocess package:

def run_sh(command):
    """Print output of bash command"""
    try:
        process = Popen(shlex.split(command), stdout=PIPE)
        for line in TextIOWrapper(process.stdout, newline=""):
            print(line)
    except CalledProcessError as e:
        raise RuntimeError(
            "command '{}' return with error (code {}): {}".format(
                e.cmd, e.returncode, e.output
            )
        )

Let's say I want to run the following from within my Python script:

run_sh(newman run MY_COLLECTION.json "--env-var 'current_branch'=`git branch --show-current`")

Currently, it does not evaluate it as git branch --show-current but just treats it like test - how do I get it to evaluate it from my shell, and then run it?

Thanks!

1 Answers

Here's a code snippet that might help


import subprocess

def run_command(cmd):
    try:
        proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = proc.communicate()
        if out:
            print(out.decode())
        if err:
            print(err.decode())
    except Exception as e:
        print(e)

if __name__ == '__main__':
    run_command('ls -l')
    run_command('ls -l /tmp')
    run_command('ls -l /tmp1')
Related