0

I must be missing something here when I try to populate a tuple in a for loop.

    ...more code above...
    colItems = objSWbemServices.ExecQuery(queryString)

#print type(colItems)

Is the above line needed?

# print the results
for item in colItems:
    logTuple = (item.SourceName, item.Type, item.TimeGenerated, item.Message)
logTuple.sort(sortByTime)
return logTuple

Would the above code enter those fields into a tuple?

Below is the code to sort, I haven't been able to test it yet though.

def sortByTime(t1, t2):
        if t1[2] < t2[2]:
            return -1
        elif t1[2] > t2[2]:
            return 1
        else:
            return 0

Thanks for the help.

2 Answers 2

1

I'm not familiar with ExecQuery or the structures you're using, but I do know that in your for loop you're rewriting logTuple each time the body of the loop is executed. This should do the trick:

logTuples = []
for item in colItems:
    logTuples.append( (item.SourceName, item.Type, item.TimeGenerated, item.Message) )
logTuples.sort(key=operator.itemgetter(2)) #credit: Thomas Jung
return logTuples
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, my bad about updating your time function, it was fine the first time. Silly me. Check out Thomas Jung version to sort; it's better. I've updated my post to reflect that
0

What you probably meant was to add the tuple to the list (and not to set logTuple to the last created tuple in the for loop):

for item in colItems:
    log = (item.SourceName, item.Type, item.TimeGenerated, item.Message)
    logTuple.append(log)

The sorting can be done with:

logTuples.sort(key=operator.itemgetter(2))

4 Comments

But you can't append to a tuple ?
You can do l.append((1,)).
This is what i get then: C:\work in progress>ntlogdata.py <type 'instance'> Traceback (most recent call last): File "C:\work in progress\ntlogdata.py", line 20, in <module> print colItems.SourceName, colItems.Type, colItems.TimeGenerated, colItems.M essage File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 516, in getattr raise AttributeError("%s.%s" % (self._username_, attr)) AttributeError: <unknown>.SourceName C:\work in progress>
With your input data colItems.SourceName cannot be evaluated. The attribute colItems.SourceNameis missing in colItems. You probably meant item.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.