如何在python中运行多行bash命令?

时间:2017-02-18 06:51:31

标签: python bash subprocess

我想在python程序中运行以下几行linux bash命令。

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.call(['my','command'])

但是,如果多行中有多个命令,我怎么能使用subprocess.call

2 个答案:

答案 0 :(得分:6)

引用https://mail.python.org/pipermail/tutor/2013-January/093474.html
使用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)

我已经尝试了其他一些例子并且有效。

答案 1 :(得分:1)

这是一个纯粹的python解决方案,我认为与您的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)