猿问

Python:创建字典

#---------------------------------------------------------

#  Print days diff by Converting Unix timestamp to Readable Date/time

#---------------------------------------------------------

def convUnixTime(t):

        return 1+(datetime.datetime.fromtimestamp(t*60*60*24)

              - datetime.datetime.today()).days



#---------------------------------------------------------

# Read shadow file and check for account expires and create dictionary 

#---------------------------------------------------------

with open( "/etc/shadow" ) as shadow:

        for aLine in shadow:

                filed = aLine.split(":")

                f = filed[7]

                try:

                    f = int(f)

                    f=convUnixTime(f)

                except ValueError:

                    f = "NULL"

                if f != "NULL" and f <= 0:

                        total_expired_users += 1

                        expr_list[ filed[0] ] = f

                elif f != "NULL" and f <= min_days:

                        total_expring_users += 1

                        expr_list[ filed[0] ] = f

我已经创建了帐户已过期的用户词典,但是我认为这样做更加简洁明了。


斯蒂芬大帝
浏览 234回答 3
3回答

弑天下

使用try-except子句可能看起来更干净:try:&nbsp; &nbsp; f = int(f)&nbsp; &nbsp; f=convUnixTime(f)except ValueError:&nbsp; &nbsp; passelse:&nbsp; &nbsp; if f <= 0:&nbsp; &nbsp; &nbsp; total_expired_users += 1&nbsp; &nbsp; &nbsp; expr_list[ filed[0] ] = f&nbsp; &nbsp; elif f <= min_days:&nbsp; &nbsp; &nbsp; total_expring_users += 1&nbsp; &nbsp; &nbsp; expr_list[ filed[0] ] = f您也可以稍微更改顺序,以避免expr_list[filed[0]]重复:if f <= min_days:&nbsp; &nbsp; expr_list[filed[0]] = f&nbsp; &nbsp; if f <= 0:&nbsp; &nbsp; &nbsp; &nbsp; total_expired_users += 1&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; total_expiring_users += 1
随时随地看视频慕课网APP

相关分类

Python
我要回答