【问题标题】:subprocess.check_output logical errorsubprocess.check_output 逻辑错误
【发布时间】:2015-12-11 23:44:24
【问题描述】:

我正在使用 subprocess.check_output 运行 Xyce(SPICE 模拟器)模拟,因为我想使用它的结果进行进一步分析。

这是我正在使用的代码:

x=subprocess.check_output(['./Xyce','Circuit.cir'])
volt=[]
for i in range(1,4): 
    start=x.find('FINAL_COL{}_VOLT = ' .format(i)) + 18

    end=x.find('Measure Start Time')

    volt.append(x[start:end])
print colored ('volt=','cyan')  

这是我为 Xyce 模拟获取的日志:

FINAL_COL1_VOLT = 0.0145203
Measure Start Time= 0   Measure End Time= 1
FINAL_COL2_VOLT = 0.0176678
Measure Start Time= 0   Measure End Time= 1
FINAL_COL3_VOLT = 0.0811186
Measure Start Time= 0   Measure End Time= 1

我得到了volt=[' 0.0145203\n','',''] 的结果,我期待得到volt=[' 0.0145203\n',' 0.0176678\n',' 0.0811186\n']。我做了一些调试,发现问题出在我的end 上,因为'Measure Start Time' 在每个结果之后都会重复。因此,当我尝试将 end 更改为另一个字符串时,代码通过了,但当然没有给我所需的输出,因为我在获得 VOLT 值后并没有停止。

所以,关于如何解决这个问题的想法。

提前致谢

【问题讨论】:

  • x.find('Measure Start Time') 返回 first Measure Start Time 的索引
  • 试试x.rfind(,,,),也可能是 grep 或 re 的工作,而不是尝试切片

标签: python python-2.7 subprocess


【解决方案1】:

您没有为Measure Start Timefind 提供偏移量。将第二个find 更改为:

end=x.find('Measure Start Time', start)

并且end 的搜索将从您确定的start 开始,而不是字符串的开头(总是找到相同的end)。

【讨论】:

    【解决方案2】:

    如果您想要所有电压 re 可能是更好的方法:

    lines = """FINAL_COL1_VOLT = 0.0145203
    Measure Start Time= 0   Measure End Time= 1
    FINAL_COL2_VOLT = 0.0176678
    Measure Start Time= 0   Measure End Time= 1
    FINAL_COL3_VOLT = 0.0811186
    Measure Start Time= 0   Measure End Time= 1"""
    
    import re
    
    print(re.findall(r"(?<=_VOLT =\s)\d+\.\d+", lines))
    ['0.0145203', '0.0176678', '0.0811186']
    

    或者分割线拉出你想要的线:

    print([line.split()[-1] for line in lines.splitlines() if line.startswith("FINAL")])
    ['0.0145203', '0.0176678', '0.0811186']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多