Omid1989
Omid1989

Reputation: 429

How to run multi-line bash commands inside python?

I want to run the following lines of linux bash commands inside a python program.

tail /var/log/omxlog | stdbuf -o0 grep player_new | while read i
do
    Values=$(omxd S | awk -F/ '{print $NF}')
    x1="${Values}"
    x7="${x1##*_}"
    x8="${x7%.*}"
    echo ${x8}
done

I know that for a single-line command, we can use the following syntax:

subprocess.call(['my','command'])

But, how can I use subprocess.call if there are several commands in multiple lines !?

Upvotes: 5

Views: 14638

Answers (2)

Stephen Rauch
Stephen Rauch

Reputation: 49784

Here is a pure python solution that I think does the same as your bash:

logname = '/var/log/omxlog'
with open(logname, 'rb') as f:
    # not sure why you only want the last 10 lines, but here you go
    lines = f.readlines()[-10:]

for line in lines:
    if 'player_new' in line:
        omxd = os.popen('omxd S').read()
        after_ = omxd[line.rfind('_')+1:]
        before_dot = after_[:after_.rfind('.')]
        print(before_dot)

Upvotes: 1

wt.cc
wt.cc

Reputation: 333

quote https://mail.python.org/pipermail/tutor/2013-January/093474.html:
use subprocess.check_output(shell_command, shell=True)

import subprocess
cmd = '''
tail /var/log/omxlog | stdbuf -o0 grep player_new | while read i
do
    Values=$(omxd S | awk -F/ '{print $NF}')
    x1="${Values}"
    x7="${x1##*_}"
    x8="${x7%.*}"
    echo ${x8}
done    
'''
subprocess.check_output(cmd, shell=True)

I have try some other examples and it works.

Upvotes: 15

Related Questions