2017-02-18 119 views
2

我想在Python程序中運行以下幾行linux bash命令。如何在python中運行多行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

我不知道這是一個妥善的解決辦法,但在bash,那麼你可以替換多行半-colons。例如,'tail/var/log/omxlog | stdbuf -o0 grep plater_new |同時閱讀我;做值= $(omxd S | awk -F /'{print $ NF}'); x1 =「$ {Values}」; ...'等等。它當然不是很可讀,但它應該工作。是否有任何理由,你不能有一個bash腳本來運行? – Guest

+0

爲什麼你不能把它放在腳本中呢? – Inian

+1

在這篇文章中有一些關於使用subprocess.pipe的好東西。http://stackoverflow.com/a/13332300/1113788另一種選擇可能是查看具有執行本地代碼和遠程代碼的各種選項的python結構庫 – davidejones

回答

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) 
+0

感謝@StephenRauch的回答。這是我對bash的第一個問題:http://unix.stackexchange.com/questions/345374/how-to-get-the-last-words-of-the-line-in-log它可能有助於精確的python解。感謝您的時間和支持十億。 – Omid1989

+1

@ Omid1989 - OH,你在上面的例子中不用'-f' ....現在它確實更有意義。 –

+0

是的,我刪除了'-f',因爲如果收到某個代碼,我想通過SPI發送'x8'變量。 (Raspberry Pi 3) – Omid1989

2

報價https://mail.python.org/pipermail/tutor/2013-January/093474.html
使用subprocess.check_output(shell_command,殼=真)

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) 

我有嘗試一些其他的例子,它的工作原理。