【问题标题】:Need an output line by line as list after executing commands inside python script在python脚本中执行命令后需要逐行输出作为列表
【发布时间】:2018-04-19 14:43:22
【问题描述】:

当我在 python 脚本中执行命令时:

import os
import re

tes=list()
tes=os.system('p4 nc files @=4596830')

for line in tes:
     line2=re.findall('//depot/prod/DOT/dev/\w+((?:/\w*)*\.c)',line)
     print(line2)

我得到的输出是:

//depot/prod/DOT/dev/freebsd/10/sys/dev/nvme/nvme.c#16 - edit change 4596830 (text)
//depot/prod/DOT/dev/mgmtgateway/src/tables/card.smf#12 - edit change 4596830 (text)
//depot/prod/DOT/dev/ontap/prod/driver/scsi/pmcsas_init.c#81 - edit change 4596830 (text)

TypeError: 'int' object has no attribute '__getitem__'

但我只需要以 .c 扩展名结尾的文件:

/freebsd/10/sys/dev/nvme/nvme.c
/ontap/prod/driver/scsi/pmcsas_init.c

【问题讨论】:

    标签: python python-2.7 subprocess os.system


    【解决方案1】:

    os.system 返回调用的状态码,而不是STDOUT, STDERR 流。 Python 不知道如何迭代一个整数,所以它会引发一个异常。

    您可以尝试使用subprocess 和管道STDOUT, STDERR 到自定义流,然后将其转换为list

    import subprocess
    
    call = subprocess.Popen("p4 nc files @=4596830", stdout=subprocess.PIPE)
    stdout = call.communicate()[0]
    files = stdout.split("\n")
    

    【讨论】:

    • tes=subprocess.Popen(["p4 nc files @=4596830"],stdout=subprocess.PIPE) output=test.communicate()[0] print(output)
    【解决方案2】:

    这可能会有所帮助

    import os
    import re
    
    tes=list()
    tes=os.system('p4 nc files @=4596830')
    
    for line in tes:
         #line2=re.findall('//depot/prod/DOT/dev/\w+((?:/\w*)*\.c)',line)
         if ".c" in line:
             print(line)
    

    【讨论】:

    • OP 得到一个TypeErroros.system 调用,所以主要问题就在那里。此外,如果“.c”在字符串中,并不意味着字符串以“.c”结尾(尽管您可以使用str.endswith(".c")
    猜你喜欢
    • 2014-08-31
    • 2012-07-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 2022-06-18
    • 2020-08-04
    • 2014-11-17
    相关资源
    最近更新 更多