【问题标题】:How to save the output of a linux command in dictionary?如何将linux命令的输出保存在字典中?
【发布时间】:2019-09-05 18:44:09
【问题描述】:

我正在尝试获取所有文件的列表以及键值对中的修改时间。

我尝试使用 subprocess.check_output("ls -lh | grep -v '^d' | awk '{print $9,$8}'", shell=True ) 存储输出,但它正在返回me 字节我无法将其转换为字典。

text = subprocess.check_output("ls -lh | grep -v '^d' | awk '{print $9,$8}'", shell=True)

【问题讨论】:

    标签: python


    【解决方案1】:

    首先在输出上调用.decode(),以便您使用字符串。然后你将不得不做一些strip 和split 魔法来构造字典:

    import subprocess
    
    output = subprocess.check_output("ls -lh | grep -v '^d' | awk '{print $9,$8}'", shell=True).decode()
    
    d = {}
    for line in output.split('\n'):
        line = line.strip()
        if line:
            file_name, mod_time = line.split()
            d[file_name] = mod_time 
    
    print(d)
    

    【讨论】:

      【解决方案2】:

      使用.decode() 方法将字节转换为字符串。如:

      text = subprocess.check_output("ls -lh | grep -v '^d' | awk '{print $9,$8}'", shell=True).decode('utf-8')
      
      

      我假设你会从这里处理剩下的?

      【讨论】:

        猜你喜欢
        • 2021-02-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-13
        • 2017-11-30
        • 1970-01-01
        • 1970-01-01
        • 2011-06-28
        • 1970-01-01
        相关资源
        最近更新 更多