Question

URGENT: Sort by Date , Python Script output

Asked by: Dushan911

Hi Experts,
This is continuing from http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_24609340.html

This is printing the failed eids.

I want to print time-process-complete tag and I want to sort output by this tag.

I'm using python 2.3

BR Dushan

import glob
import os
import sys
import xml.dom.minidom
 
def listOfFailed(fname):
 
    # Parse the existing file
    #
    assert os.path.isfile(fname)
    dom = xml.dom.minidom.parse(fname)
     
    # Initialize the resulting list for the eids
    # of the failed documents and then parse the file
    # and collect the info.
    #
    result = []
    for doc in dom.getElementsByTagName('doc'):    # through all doc elements
        lst = doc.getElementsByTagName('status')   
        assert len(lst) == 1                       # a doc should contain a single status element
        status = lst[0].firstChild.data            # the text of the status element
     
        if status == u'failed':                    # pay attention to unicode
            lst = doc.getElementsByTagName('eid')  
            assert len(lst) == 1                   # the doc should contain a single eid element
            eid = lst[0].firstChild.data           # the eid value as text 
            
            result.append(eid)                     # display eid of the failed doc
        else :
                        
            continue
            
    # Return the collected information.
    return result
            
            
if __name__ == '__main__':
    myPath = '.'               # default path
    if len(sys.argv) > 1:
        myPath = sys.argv[1]   # explicit path to your xml files
        
    # Get all XML file nams from the path and process them.
    #
    for fname in glob.glob(os.path.join(myPath, '*.xml')):
        lst = listOfFailed(fname)   # get the failed eids
        if len(lst) > 0:
            print fname
            for eid in lst:
                print '\t' + eid

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-28 at 08:44:28ID24690172
Tags

Python

Topics

Python Scripting Language

,

C++ Programming Language

,

Regular Expressions

Participating Experts
2
Points
500
Comments
19

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Python Webserver
    hi All, I am trying out something in python and urgently need help. I have a python program which reads and stores data in a database. I wan to write a webserver in python (I have had a crack at it but stack) which will do the following: POST - I would like the do_POST meth...
  2. Outputting HTML in Python
    Am a total python newbie. I have written soem scripts for pasring HTML, and spitting output in txt file format. Am mostly a PHP and ASP.NET web dev. So my question is from that perspective. In PHP for example i could output to a webpage like so: <?php $sGreeting = ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Dushan911Posted on 2009-08-28 at 08:45:45ID: 25208848

Input XML is below format as mentioned in http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_24609340.html

<documents>
  <doc>
    <eid>766877_765765765_load</eid>
    <reporter>dushan</reporter>
    <trans-type>add</trans-type>
    <status>failed</status>
    <time-req-received>1287660397</time-req-received>
    <time-process-start>2009-07-22T19:48:34+00:00</time-process-start>
    <time-process-complete>2007-05-22T20:00:00+00:00</time-process-complete>
    <load-unit-id></load-unit-id>
    <item-transaction-id></item-transaction-id>
    <status-detail>processing failure</status-detail>
  </doc>
  <doc>
    <eid>123456789</eid>
    <reporter>dushan</reporter>
    <trans-type>add</trans-type>
    <status>success</status>
    <time-req-received>987654321</time-req-received>
    <time-process-start>2009-07-16T03:01:26+00:00</time-process-start>
    <time-process-complete>2009-07-16T06:00:00+00:00</time-process-complete>
    <load-unit-id></load-unit-id>
    <item-transaction-id></item-transaction-id>
    <status-detail></status-detail>
  </doc>
  <doc>
    <eid>6789123455</eid>
    <reporter>dushan</reporter>
    <trans-type>add</trans-type>
    <status>success</status>
    <time-req-received>5543219876</time-req-received>
    <time-process-start>2009-07-16T03:01:50+00:00</time-process-start>
    <time-process-complete>2009-07-16T06:00:00+00:00</time-process-complete>
    <load-unit-id></load-unit-id>
    <item-transaction-id></item-transaction-id>
    <status-detail></status-detail>
  </doc>
</documents>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:

Select allOpen in new window

 

by: HonorGodPosted on 2009-08-28 at 12:37:55ID: 25210962

What do you want printed, and in what format?

 

by: Dushan911Posted on 2009-08-28 at 20:28:24ID: 25212907

I want to print time-process-complete and eid.
Sort by time-process-complete and eid.

 

by: HonorGodPosted on 2009-08-28 at 20:31:19ID: 25212912

Do you have any idea how large the input files are?

In other words, can the script read the input with a single read, or should the data be processed one record at a time?

 

by: Dushan911Posted on 2009-08-28 at 20:43:46ID: 25212926

input is large, all together file size greater than 135MB. Above attached code  I tested with these files and taking more than 2 hours to complete. But that's fine for moment.

 

by: peprPosted on 2009-08-30 at 22:54:07ID: 25220719

Two hours seems too much to me (for 135 MB). How many records are expected in the result list (i.e. tens, hundreds, thousands, millions)?

The long processing time could be because of the xml.dom.minidom principal features and also because not of its inefficient implementation in Python. I suggest to use the SAX parser in this case. Try the snippet below. The way of compounding the line with info is because of the sorting. It can be generalized -- the info can be collected to tuples, then sort can be done via supplying your own comparison function, and printing the result can also be customized.

I have tested it only with your sample -- one line in result like (tab separated):

2007-05-22T20:00:00+00:00       766877_765765765_load   .\doc.xml

# The script must work with Python 2.3. This way some
# newer features of Python or newer standard moduled 
# cannot be used. SAX parser used.
 
import glob
import os
import sys
import xml.sax
 
class DocHandler(xml.sax.handler.ContentHandler):
    '''The class for handling the SAX parser events.'''
 
    def __init__(self, lst, fname):
        xml.sax.handler.ContentHandler.__init__(self) # init through the base class code
        self.fname = fname # the processed file name
        self.status = []   # for collecting the characters inside the status element
        self.eid = []      # for collecting the characters inside the eid element
        self.tpc = []      # for collecting the characters inside the time-process-complete element
        self.elem = None   # reference to the current container for collecting the chars
        self.lst = lst     # reference to the list of results (not initialized here)
        
 
    def startElement(self, name, attrs):
 
        if name == 'doc':
            # New doc element found. Erase the previously collected status/eid chars.
            self.status = []
            self.eid = []
            
        elif name == 'status':
            # The status element starts. Let's collect the text into self.status.
            self.elem = self.status
            
        elif name == 'eid':
            # The eid element starts. Let's collect the text into self.eid.
            self.elem = self.eid
            
        elif name == 'time-process-complete':
            # The time-process-complete element starts. Collect into self.tpc.
            self.elem = self.tpc
 
        
    def characters (self, ch):
        # If any container for collecting the text is referred, do collect
        # the character into the referred list.
        if self.elem is not None:
            self.elem.append(ch)
 
 
    def endElement(self, name):
        if name == 'doc':
            # The doc element was closed. Process the collected info.
            # Join the lists of collected characters into a string.
            status = ''.join(self.status)  
            eid = ''.join(self.eid)
            tpc = ''.join(self.tpc)
            
            # Collect the compound string of tpc, eid, and file name.
            if status == u'failed':
                self.lst.append(tpc + u'\t' + eid + u'\t' + self.fname)
                
        elif name == 'status':
            self.elem = None               # stop collecting the chars to the self.status 
        elif name == 'eid':
            self.elem = None               # stop collecting the chars to the self.eid
        elif name == 'time-process-complete':
            self.elem = None               # stop collecting the chars to the self.tpc
            
 
def listOfFailed(fname):
    '''Returns the list of eids of the failed documents.'''
    
    # Initialize the resulting list for the eids
    result = []
    
    # Create parser and collect the eid during parsing. 
    parser = xml.sax.make_parser()         # create the SAX XMLReader object
    docHandler = DocHandler(result, fname) # create the object for handling events
    parser.setContentHandler(docHandler)   # use the handler for the parser
    parser.parse(fname)                    # parse
 
    # Return the collected information.
    return result
    
    
def main():
    myPath = '.'               # default path
    if len(sys.argv) > 1:
        myPath = sys.argv[1]   # explicit path to your xml files
        
    # Get all XML file names from the path and process them.
    # Extract the list of failed docs from all xml files into
    # one resultLst.
    resultLst = []
    for fname in glob.glob(os.path.join(myPath, '*.xml')):
        lst = listOfFailed(fname)   # get the failed eids records (as strings)
        resultLst.extend(lst)
 
    # Sort and pring the resulting list.
    resultLst.sort()
    for line in resultLst:
        print line
                
                
if __name__ == '__main__':
    main()
                

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:

Select allOpen in new window

 

by: Dushan911Posted on 2009-08-31 at 02:39:59ID: 25221493

Thanks a lot! but when I'm executing this script against my list of all files( 138MB), it gives following error.

---------------------------------------------------------------------------------------------------------
  File "feedback_failed.py", line 113, in ?
    main()
  File "feedback_failed.py", line 103, in main
    lst = listOfFailed(fname)   # get the failed eids records (as strings)
  File "feedback_failed.py", line 87, in listOfFailed
    parser.parse(fname)                    # parse
  File "lib/python2.3/xml/sax/expatreader.py", line 107, in parse
  File "lib/python2.3/xml/sax/xmlreader.py", line 123, in parse
  File "lib/python2.3/xml/sax/expatreader.py", line 207, in feed
  File "lib/python2.3/xml/sax/expatreader.py", line 303, in end_element
  File "feedback_failed.py", line 67, in endElement
    self.lst.append(tpc + u'\t' + eid + u'\t' + self.fname)
MemoryError
---------------------------------------------------------------------------------------------------------


Earlier with dom , I didn't get such error. Only thing was it's getting more than 2 hours time.


Please let me know best solution.

Thanks again!

Dushan.

 

by: peprPosted on 2009-08-31 at 03:17:08ID: 25221625

I cannot try it with Python 2.3. Try to remove the Unicode prefix on the line 60:

self.lst.append(tpc + '\t' + eid + '\t' + self.fname)

 

by: peprPosted on 2009-08-31 at 03:18:39ID: 25221631

or try
   self.lst.append('%s\t%s\t%s' % (tpc, eid, self.fname))

 

by: Dushan911Posted on 2009-08-31 at 06:10:06ID: 25222441

I'm getting same error for both of above line...

 

by: Dushan911Posted on 2009-08-31 at 06:18:56ID: 25222505

File "feedback_failed.py", line 115, in ?
    main()
  File "feedback_failed.py", line 105, in main
    lst = listOfFailed(fname)   # get the failed eids records (as strings)
  File "feedback_failed.py", line 89, in listOfFailed
    parser.parse(fname)                    # parse
  File "lib/python2.3/xml/sax/expatreader.py", line 107, in parse
  File "lib/python2.3/xml/sax/xmlreader.py", line 123, in parse
  File "lib/python2.3/xml/sax/expatreader.py", line 207, in feed
  File "lib/python2.3/xml/sax/expatreader.py", line 303, in end_element
  File "feedback_failed.py", line 63, in endElement
    tpc = ''.join(self.tpc)
MemoryError

 

by: peprPosted on 2009-08-31 at 06:28:38ID: 25222576

Well, then the opposite approach may be needed. The problem is that based on the XML encoding, the collected characters (i.e. one character strings) could be the Unicode ones. Can you post a simplified example of a XML file that is to be processed by the script and that causes the error? I'll try to install the Python 2.3...

Meanwhile, you can try to use something like
    tpc = u''.join(self.tpc)
instead of
    tpc = ''.join(self.tpc)

(also in other similar cases) and the
    self.lst.append(u'%s\t%s\t%s' % (tpc, eid, self.fname))
instead of
    self.lst.append('%s\t%s\t%s' % (tpc, eid, self.fname))

 

by: peprPosted on 2009-08-31 at 06:50:39ID: 25222750

Well, I have just installed Python 2.3.5 and converted the script to use (blindly, mechanically) the Unicode string literals only -- saved in UTF-8 with Signature, LF ended lines. The same way, the doc.xml was converted. It runs without errors on my Windows machine. I do not have Linux at hands. Try to unzip and run the attached file.

  • example.zip
    • 2 KB

    Unzip and remove the .txt extension required by EE

 

by: Dushan911Posted on 2009-08-31 at 07:07:15ID: 25222879

Thanks! but I'm sorry to say that still same error.. :( .. seems memory usage is good in here in sax.. shall we try with dom?

 

by: Dushan911Posted on 2009-08-31 at 07:12:15ID: 25222918

sorry memory usage seems not goood in sax .. shall we try with dom.. because for dom it works fine earlier..

 

by: Dushan911Posted on 2009-08-31 at 08:55:22ID: 25223813

can u provide me how to capture exact error with this code using try, catch ..etc

 

by: peprPosted on 2009-08-31 at 14:44:41ID: 25226813

OK. Here is the minidom version. Anyway, I guess that SAX would really be much faster here. It is a pitty that you observe the error.

import glob
import os
import sys
import xml.dom.minidom
 
def listOfFailed(fname):
 
    # Parse the existing file
    #
    assert os.path.isfile(fname)
    dom = xml.dom.minidom.parse(fname)
     
    # Initialize the resulting list for the eids
    # of the failed documents and then parse the file
    # and collect the info.
    #
    result = []
    for doc in dom.getElementsByTagName('doc'):    # through all doc elements
        lst = doc.getElementsByTagName('status')   
        assert len(lst) == 1                       # a doc should contain a single status element
        status = lst[0].firstChild.data            # the text of the status element
     
        if status == u'failed':                    # pay attention to unicode
            lst = doc.getElementsByTagName('eid')  
            assert len(lst) == 1                   # the doc should contain a single eid element
            eid = lst[0].firstChild.data           # the eid value as text 
            
            lst = doc.getElementsByTagName('time-process-complete')  
            assert len(lst) == 1
            tpc = lst[0].firstChild.data
            
            result.append('%s\t%s\t%s' % (tpc, eid, fname))
        else:
            continue
            
    # Return the collected information.
    return result
            
            
if __name__ == '__main__':
    myPath = '.'               # default path
    if len(sys.argv) > 1:
        myPath = sys.argv[1]   # explicit path to your xml files
        
    # Get all XML file names from the path and process them.
    # Collect all results to the result list.
    resultLst = []
    for fname in glob.glob(os.path.join(myPath, '*.xml')):
        lst = listOfFailed(fname)   # get the failed eids
        resultLst.extend(lst)
        
    # Sort the result list and print it.
    resultLst.sort()
    for rec in resultLst:
        print rec    
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:

Select allOpen in new window

 

by: Dushan911Posted on 2009-08-31 at 21:21:01ID: 31621767

This is superb! I'm getting results within 15 minutes time now.

 

by: Dushan911Posted on 2009-08-31 at 22:10:44ID: 25228662

I would greatly appreciate that if you could look at this also. :)


http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_24696936.html

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...