そのような文字列を見つけてJob 'Initialize' completed successfully
、Python からこのコマンドを実行する必要があります。
シェルgrep -c "Job 'Initialize' completed" 1.log
は正常に動作しますが、このコマンドはPythonでどのように見えますか? cmd = """grep -c "Job 'Initialize' completed" 1.log"""
?
これは、サブプロセスで簡単に実行できます。
subprocess.call(['grep','-c',"Job 'Initialize' completed", '1.log'])
Python を使用する場合は、Python を使用します。
with open('1.log') as f:
count = 0
for line in f:
if "Job 'Initialize' completed" in line:
count += 1
print "Count: {}".format(count)
また
with open('1.log') as f:
count = sum(1 for line in f if "Job 'Initialize' completed" in line)
print "Count: {}".format(count)
シェル コマンドは、三重引用符を使用し、shell=True を subprocess.call に渡すことで、Python でそのまま実行できます。ドキュメントによると、「信頼されていない入力と組み合わせると、shell=True を使用してシステム シェルを呼び出すと、セキュリティ上の危険が生じる可能性があります」ということに注意してください。
subprocess.call(''' grep -c "Job 'Initialize' completed" 1.log ''', shell=True)