使用os.system中的grep的Python将"0"行添加到变量中?

Tur*_*tle 0 python grep

我正在python脚本中运行grep,如下所示:

last_run_start = os.system("cat %(file)s | grep '[0-24]:[0-59]' | tail -n1" % locals())

这拉出了最后一个时间戳file.当我通过Python命令行执行此操作,或通过常规终端使用该grep命令时,我得到了预期的结果 - 包含时间戳的最后一行.

但是,从此脚本运行时last_run_start返回此:

18:23:45

0
Run Code Online (Sandbox Code Playgroud)

什么原因导致这个'0'出现,更不用说换新线了?更重要的是,我该如何将其删除last_run_start

mat*_*ata 5

os.system 返回您运行的命令的退出代码,在这种情况下似乎为0.

如果您希望使用或来自模块,则命令的输出直接进入stdout并且不存储.last_run_startPopencheck_outputsubprocess

我猜0最终会被打印,因为你正在打印last_run_startsomwhere.