2017-02-18 30 views
2

私はPythonプログラム内でlinux bashコマンドの次の行を実行したいと思います。複数行でいくつかのコマンドがあるかどうか、私はsubprocess.callを使用することができ、pythonの中で複数行のbashコマンドを実行するには?

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

しかし:

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 

私は、1行のコマンドのために、我々は次の構文を使用することができます知っていますか!?

+2

私は、これは適切な解決策であることを知りませんが、bashで、あなたが半で複数行を置き換えることができますコロンたとえば、 'tail/var/log/omxlog | stdbuf -o0 grep plater_new |読んでいる間はi; do Values = $(omxd S | awk -F/'{print $ NF}'); x1 = "$ {値}"; ... ...と続きます。確かにあまり読みにくくはありませんが、うまくいくはずです。あなたが代わりに実行するbashスクリプトを持つことができなかった理由はありますか? – Guest

+0

代わりにスクリプトに入れられないのはなぜですか? – Inian

+1

この記事には、subprocess.pipeの使用に関するいくつかの良いことがあります。http://stackoverflow.com/a/13332300/1113788別のオプションは、ローカルとリモートのコードを実行するためのさまざまなオプションを持つpythonファブリックライブラリを見ることです。 – davidejones

答えて

1

は、私はがあなたのbashと同じ処理を行いだと思う純粋なPythonのソリューションです:

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に役立つかもしれない溶液。あなたの時間とサポートのために10億に感謝します。 – Omid1989

+1

@ Omid1989 - オハイオ州、あなたは上記のあなたの例で '-f'を中止しました....今は少し意味があります。 –

+0

はい特定のコードが受信された場合、SPI経由で 'x8'変数を送信したいので、' -f'を削除しました。 (ラズベリーパイ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) 

私はいくつかの他の例を試してみると、それは動作します。ここで

関連する問題