2017-10-22 12 views
0

何をしようとしているのかを説明するコードをいくつか書きました。私はちょうど正しい構文を得るように思わない、誰かが助けることができる?pgrepを実行してpidの実行時間を確認します

def calc_execution(): 
    import subprocess 
    #get the proc id of detectmotion; need help converting into subprocess 
    detectmotion_file_pid = subprocess.call(pgrep -f "detectmotion.py") 
    if detectmotion_file_pid: 
     #determine how long pid has been running; note this seems to be incorrect 
     len_run_time=subprocess.call(ps -o etime= -p detectmotion_file_pid) 
     print len_run_time 

私の問題は、正しく動作するためにVAR detectmotion_file_pidlen_run_timeの構文を取得しています。

誰かが助けてくれますか?

おかげ

+0

@Attie更新参照してください。 – John

答えて

0

subprocess.call()argsパラメータとして文字列または文字列の配列を期待する - ドキュメントhereを参照してください。

あなたが提供している:としてPythonによって解釈される

subprocess.call(pgrep -f "detectmotion.py")、:

  • が変数pgrepの値を取り、および減算をf
  • 文字列 "detectmotion.py"

Wh

subprocess.call([ 'pgrep', '-f', 'detectmotion.py']) 

この配列の各項目は、次のプロセスの引数として使用されます。 pgrepは、実行するバイナリを示します(新しいプロセスではarg 0として表示されます)。 -fdetectmotion.pyは次の引数です。

ランタイムを取得する場合は、同じことをもう一度やり直してください。 - 次のような簡単な修正があります。

subprocess.call(['ps', '-o', 'etime=', '-p', detectmotion_file_pid ]) 

最後の問題は、あなたがsubprocess.call()の戻り値はあなたが後にしているデータであることを期待しているということです。実際には、subprocess.call()は:

returncode属性を返します。物事が取得する場所

あなたはちょうど走ったコマンドの出力をキャッチしたい場合は、あなたがあなたのアプリケーションにコマンドの出力をもたらすために、「パイプ」を使用する必要がありますが、これはあります乱雑には、ドキュメントは言う:

注:それは子プロセスの出力ボリュームに基づいてデッドロックすることができますようは、この機能を標準出力= PIPEまたはstderr = PIPEを使用しないでください。パイプが必要な場合は、communicate()メソッドでPopenを使用できます。

So ...

x = subprocess.Popen([ 'pgrep', '-f', 'detectmotion.py']) 
out, _ = x.communicate() 

# out is currently a string, e.g: '26585\n' 
print(out) 

# convert it into an integer: 
detectmotion_file_pid = int(out.rstrip()) 

これはあなたの人間が読める形式で時刻を返しますようあなたは、ps -o etime= -p ...の出力と似た何かをする必要があります。この時点で

x = subprocess.Popen(['ps', '-o', 'etime=', '-p', str(detectmotion_file_pid) ]) 
out, _ = x.communicate() 

# out is currently a string, e.g: '  12:53\n' 
print(out) 

# strip it 
out = out.strip() 

# now it's free of white-space, e.g: '12:53' 
print(out) 

、あなたは残念ながらpsの出力は、人間のために設計された、おそらくにひどく単純ではありません...どのようにもっと便利なものに一見mm:ssフォーマットを変換するために自分自身を頼むかもしれませんこのように解析する。

あなたはあなたのプロセスに関する情報のすべての種類を伝えることができ、/proc/[pid]/statに見えることを好むかもしれません:

関連する問題