我需要找到这样的字符串Job 'Initialize' completed successfully
并从python运行此命令。
所以shell grep -c "Job 'Initialize' completed" 1.log
工作正常但是这个命令在python中看起来怎么样? cmd = """grep -c "Job 'Initialize' completed" 1.log"""
?
答案 0 :(得分:3)
这对子进程很容易:
subprocess.call(['grep','-c',"Job 'Initialize' completed", '1.log'])
答案 1 :(得分:3)
如果你想使用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)
答案 2 :(得分:0)
shell命令可以在python中以三引号的形式执行,并将shell = True传递给subprocess.call。请注意,根据文档“如果与不受信任的输入结合使用,则调用具有shell = True的系统shell可能存在安全隐患”
subprocess.call(''' grep -c "Job 'Initialize' completed" 1.log ''', shell=True)