基于bash输出创建python映射

时间:2014-05-13 16:12:52

标签: python bash dictionary map

如何将此输出传递给python地图对象?
基本上,我希望能够在python脚本中运行与print data.Data类似的东西 所以在终端上,所有要打印的都是

'uname' is not recognized as an internal or external command, operable program or batch file.

这是我的python脚本:

[root@server tools]# cat remoteTest.py
import sys

data = sys.stdin.read()
print data

这是我将运行命令的方式:

[root@server tools]# staf server2.com PROCESS START SHELL COMMAND 'uname' WAIT RETURNSTDOUT STDERRTOSTDOUT | python remoteTest.py
Response
--------
{
  Return Code: 1
  Key        : <None>
  Files      : [
    {
      Return Code: 0
      Data       : 'uname' is not recognized as an internal or external command,
operable program or batch file.

    }
  ]
}

2 个答案:

答案 0 :(得分:1)

如果您只对行

感兴趣
Data       : 'uname' is not recognized as an internal or external command, operable program or batch file.

您可以使用subprocess module来调用staf程序

import subprocess
output = subprocess.check_output(["staf", "server2.com PROCESS START SHELL COMMAND 'uname' WAIT RETURNSTDOUT STDERRTOSTDOUT"])

并使用正则表达式。我不喜欢正则表达式,但有时需要它。

result = re.findall(r'Data\s+:\s+(.*)', output, re.M)[0]
print result

被修改 有多线工作人员计划输出的信息

output = output.replace('\n', '')

result = re.findall(r'Data\s+:\s+(.*)}', output, re.M)[0]

<强>被修改

o = """{
   Return Code: 1
   Key        : <None>
   Files      : [
     {
       Return Code: 0
       Data       : 'uname' is not recognized as an internal or external command,
 operable program or batch file.

     }
   ]
 }"""
a = o.replace('\n', '')
import re
print re.findall('Data\s+:\s+(.+?)\}', a)[0].strip()

答案 1 :(得分:0)

这适用于您的样本。它有一些hackery来处理嵌套数组,这意味着如果嵌套数组的输出不完全是这样的话,它将无法工作:

Key: [
  <Nested content>

输入中可能会有一些其他微小的变化会破坏它,但它至少是一个开始。

#!/usr/bin/python

import ast 

a = """ 
Response
--------
{
  Return Code: 1
  Key        : <None>
  Files      : [
    {
      Return Code: 0
      Data       : 'uname' is not recognized as an internal or external command, operable program or batch file.

    }
  ]
}"""

lines = a.split("--------")[1].split('\n')
new = []
for line in lines:
    if ":" in line:
        # If the line is a mapping, split it into the part before and after the ":".
        parts = [l.strip() for l in line.split(":")]
        # Surround strings in double quotes.
        s = ': '.join(['"%s"' % i if not i.startswith("[") else i for i in parts])
        # Add a comma if it's not an embedded list.
        if not s.endswith('['):
            s += "," 
        line = s 
    if line:
        new.append(line)

d = ast.literal_eval('\n'.join(new))
print d['Files'][0]['Data']

输出:

dan@dantop:~> ./parse.py 
'uname' is not recognized as an internal or external command, operable program or batch file.