reusable function: substituting the values returned by another function

本秂侑毒 提交于 2019-12-03 21:57:25

Since you don't know LJ, LU, LH, LQ, LE until the for-loop ends, you have to complete this for-loop before you print.

    result=[]
    for line in lines:
        if line.find('Exit_status=') != -1:
            ...
            LJ = max(LJ, len(jobID))
            LU = max(LU, len(jUsr))
            LH = max(LH, len(jHst))
            LQ = max(LQ, len(jQue))
            LE = max(LE, len(eDate))
            result.append((jobID,jUsr,eDate,jHst,jQue))
   fmt="%%-%ss%%-%ss%%-%ss%%-%ss%%-%ss"%(LJ,LU,LE,LH,LQ)
   for jobID,jUsr,eDate,jHst,jQue in result:       
       print fmt % (jobID,jUsr,eDate,jHst,jQue)

The fmt line is a bit tricky. When you use string interpolation, each %s gets replaced by a number, and %% gets replaced by a single %. This prepares the correct format for the subsequent print statements.

Since the column header and column content are so closely related, why not couple them into one structure, and return an array of 'columns' from your job_history function? The task of that function would be to

  1. output the header for each colum
  2. create the output for each line, into the corresponding column
  3. remember the maximum width for each column, and store it in the column struct

Then, the prinf_fmt function can 'just'

  1. iterate over the column headers, and print them using the respective width
  2. iterate over the 'rest' of the output, printing each cell with 'the respective width'

This design will separate output definition from actual formatting.

This is the general idea. My python is not that good; but I may think up some example code later...

Depending on how many lines are there, you could:

  • read everything first to figure out the maximum field lengths, then go through the lines again to actually print out the results (if you have only a handful of lines)
  • read one page of results at a time and figure out maximum length for the next 30 or so results (if you can handle the delay and have many lines)
  • don't care about the format and output in a csv or some database format instead - let the final person / actual report generator worry about importing it
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!