Python:创建字典

标签 python unix

#---------------------------------------------------------
#  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

我已经创建了帐户已过期的用户字典,但我认为这是以更干净和简单的方式完成的。

提前致谢!!

最佳答案

使用 try-except 可能看起来更干净子句:

try:
    f = int(f)
    f=convUnixTime(f)
except ValueError:
    pass
else:
    if f <= 0:
      total_expired_users += 1
      expr_list[ filed[0] ] = f
    elif f <= min_days:
      total_expring_users += 1
      expr_list[ filed[0] ] = f

您还可以稍微更改一下顺序,以避免 expr_list[filed[0]] 重复:

if f <= min_days:
    expr_list[filed[0]] = f

    if f <= 0:
        total_expired_users += 1
    else:
        total_expiring_users += 1

关于Python:创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17079261/

相关文章:

c - 使用 NBIO 的高效预 fork 服务器设计,例如使用 libevent 的 epoll、kqueue

python - 需要一个条件语句来填充基于字符串的列

python - Django 1.8 管理表单 : AttributeError XForm object has no attribute 'save_m2m'

python - Pandas : Assigning a value for each row in certain column based on multiple if condition

python - 增加 matplotlib 字符串字体大小

Linux-awk 在一列中寻找两个变量

unix - 确定 fork/exec 成功或失败的标准方法(当父进程同时运行时)?

unix - 我如何查看正在运行的 tcsh 版本?

python - python中有类似 "set -x"的东西吗

python - 使用 Python 在 sudo 之后获取父用户