在您提到的情况下,您总是需要第二个CPU编号,因此可以使用单个正则表达式完成:
# Test program
import re
lns = [
"TrnIq: Thread on CPU 37",
"TrnIq: Thread on CPU 37 but will be moved to CPU 44",
"IP-Thread on CPU 33",
"FANOUT Thread on CPU 37",
"Filter-Thread on CPU 38 but will be moved to CPU 51",
"TRN TMR Test 2 Supervisor Thread on CPU 34",
"HomographyWarp Traking Thread[0] on CPU 26"
]
for ln in lns:
test = re.search("(?P.*Thread\S* on).* CPU (?P\d+)$", ln)
print "%s: '%s' on CPU #%s" % ( ln, test.group('process'), test.group('cpu'))在一般情况下,您可能希望区分案例(例如,CPU上的线程,移动的线程,子线程......)。为此,您可以一个接一个地使用几个re.search()。例如:
# This search recognizes lines of the form "...Thread on CPU so-and-so", and
# also lines that add "...but will be moved to CPU some-other-cpu".
test = re.search("(?P.* Thread) on CPU (?P\d+)( but will be moved to CPU (?P\d+))*", ln)
if test:
# Here we capture Process Thread, both moved and non moved
if test.group('cpu2'):
# We have process, cpu1 and cpu2: moved thread
else:
# Nonmoved task, we have test.group('process') and cpu1.
else:
# No match, try some other regexp. For example processes with a thread number
# between square brackets: "Thread[0]", which are not captured by the regex above.
test = re.search("(?P.*) Thread[(?P\d+)] on CPU (?P)", ln)
if test:
# Here we have Homography Traking in process, 0 in thread, 26 in cpu1为获得最佳性能,最好先对频繁出现的线路进行测试。