How to run multi-line bash commands inside python?

后端 未结 2 742
悲哀的现实
悲哀的现实 2021-01-25 03:59

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
d         


        
相关标签:
2条回答
  • 2021-01-25 04:20

    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.

    0 讨论(0)
  • 2021-01-25 04:26

    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)
    
    0 讨论(0)
提交回复
热议问题