Python:试图使用“count”来限制行的“打印”量。将输出 [英] Python: trying to use 'count' to limit the amount of lines "print" will output
问题描述
我有一个脚本将会走一个系统目录,并获得该目录中的文件大小。它然后按文件大小排序(降序),接受两个参数。第一个参数是系统路径,第二个参数是一个整数,以限制输出到该整数计数。
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.
我使用while循环来限制打印输出但它陷入无限循环....显然,有些事是错误的,但我看不到它。
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()
推荐答案
如果 mycnt
是一个字符串,不是一个整数(从 sys.argv
直接读取),你的循环永远不会结束。
If mycnt
is a string, not an integer (which it is when read directly from sys.argv
), your loop will never end.
这篇关于Python:试图使用“count”来限制行的“打印”量。将输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!