Python: trying to use 'count' to limit the amount of lines “print” will output

自古美人都是妖i 提交于 2019-12-25 09:41:06

问题


I have a script that will walk a system directory, and get the files sizes in that directory. it then sorts by the file size(descending), takes two arguments. The first arg is the system path and the second arg is an integer to limit the output to that integer count.

I'm using a while loop to limit the print output but its getting stuck in a infinite loop.... obviously, something is wrong but i cant see it.

#!/usr/bin/python

import sys
import os

#Grab arguments 
mydir = sys.argv[1]
mycnt = sys.argv[2]

print mydir 
print mycnt
#set base dir
root_path = mydir


fileSize = 0
rootdir = mydir
filedict = dict()
count = 0

for root, dirs, files in os.walk(rootdir):
    for file in files:
        filepath = os.path.join(root,file)
        filesize = fileSize + os.path.getsize(filepath)
        filedict[filepath] = filesize


for key, value in sorted(filedict.iteritems(), key=lambda (key,val): (val,key), reverse=True):
    while (count <= mycnt):
        print "(%8s)" "     (%-8s)" % (value, key)
        count += 1
    else:
        sys.exit()

回答1:


If mycnt is a string, not an integer (which it is when read directly from sys.argv), your loop will never end.




回答2:


FWIW, the repr module has tools to display a list while limiting the number of lines of output.




回答3:


You should have an if instead of while.

You want to exit the program if count <= mycnt.




回答4:


You added the else clause to the while loop. It will execute only if the while loop never executes.

Your while loop terminates as count increases past mycnt, and anoter iteration of for loop is executed. Mabe you just don't notice it ­— your for loop may take long.




回答5:


Larry Lustig has already hit the nail on the head regarding mycnt, but your check to see if you've hit the limit is also wrong (as Hamish points out).

Rather than if (count <= mycnt):, you could use a slice like [:maximum], removing the need for the count variable. Speaking of variables, I suggest that you would benefit from some better-named variables. Viz:

#!/usr/bin/env python

import sys
import os

rootdir = sys.argv[1]
maximum = int(sys.argv[2])

print 'Printing the biggest ', maximum, 'files in', rootdir, '...'

filedict = {}
for root, _, files in os.walk(rootdir):
    for filename in files:
        filepath = os.path.join(root, filename)
        filesize = os.path.getsize(filepath)
        filedict[filepath] = filesize

sorted_by_size = sorted(filedict.iteritems(), key=lambda(path, size): (size, path), reverse=True)
for path, size in sorted_by_size[:maximum]:
     print "(%8s)      (%-8s)" % (size, path)


来源:https://stackoverflow.com/questions/8102177/python-trying-to-use-count-to-limit-the-amount-of-lines-print-will-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!