首页 > 解决方案 > 在同一个ansible剧本中将json字符串从ansible输出传递给python

问题描述

我有 2 个脚本a.pyb.py.

我有一个运行a.pyb.py. 这是脚本的 输出a.py给的b.py。问题是输出a.py一个可以索引的列表,但是每当我将yaml作为命令行参数传递给它时,它就会作为stdout对象并且可以像以前一样被索引,即像's。b.pystra.py

脚本 a.py

a = [{
        "name": "jack",
        "date": "Jan-06-2021",
        "age": "24",
    },
    {
        "name": "jack1",
        "date": "Jan-07-2021",
        "age": "25",
    },
]
print(a)

b.py 脚本

import sys
import json
random_variable = sys.argv[1] 
print(json.loads(random_variable)) # tried this no use

我想解析alikerandom_variab.e[0]和的值random_variable[1]
random_variable[0]可能像:

{'name': 'jack', 'date': 'Jan-06-2021', 'age': '24'}
- name: testing
  gather_facts: True
  hosts: localhost
  tasks:

    - name: run python script
      command: python3 /test-repo/test_python/a.py
      register: result
    - set_fact:
        var1: "{{result.stdout}}"
    - debug: 
        msg: "{{var1}}"
    
    - name: run python script2
      command: python3 /test-repo/test_python/b.py {{var1}}
      register: result
    - debug: 
        msg: "{{result}}"

我现在遇到的错误

["Traceback (most recent call last):", "  File \"/test-repo/test_python/b.py\", line 4, in <module>", "    print(json.loads(a))", "  File \"/usr/lib64/python3.6/json/__init__.py\", line 354, in loads", "    return _default_decoder.decode(s)", " 
 File \"/usr/lib64/python3.6/json/decoder.py\", line 339, in decode", "    obj, end = self.raw_decode(s, idx=_w(s, 0).end())", "  File 
\"/usr/lib64/python3.6/json/decoder.py\", line 355, in raw_decode", "    obj, end = self.scan_once(s, idx)", "json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)"]

打印时的预期输出

random_variable = sys.argv[1]
print(random_variable[0])

我需要的输出

{'name': 'jack', 'date': 'Jan-06-2021', 'age': '24'}

标签: jsonpython-3.xansible

解决方案


您的问题并非来自b.py,就像您认为的那样。

这实际上是因为a.py不是在打印 JSON,而是在打印 python 字典,因此,您不能将它作为 JSON加载回b.py中。

在 playbook 中调试a.py的结果会给你:

[{'name': 'jack', 'date': 'Jan-06-2021', 'age': '24'}, {'name': 'jack1', 'date': 'Jan-07-2021', 'age': '25'}]

但这不是一个有效的 JSON 数组,因为正如错误消息向您提示的那样,JSON 中的字符串和属性必须用双引号而不是简单的引号括起来。

因此,您至少应该做两件事:

  1. 调整a.py并使其读取
    import json
    a = [{
            "name": "jack",
            "date": "Jan-06-2021",
            "age": "24",
        },
        {
            "name": "jack1",
            "date": "Jan-07-2021",
            "age": "25",
        },
    ]
    print(json.dumps(a))
    
  2. 调整您的剧本并将您的 JSON 字符串用简单的引号引起来,以免破坏外壳:
    - command: python3 /test-repo/test_python/b.py '{{ var1 }}'
    

这就是说,我也会做出这样的调整:在你的 Python 脚本中使用适当的shebang,这样你就不必再为command任务指定解释器了。

所以a.py变成:

#!/usr/bin/env python3
import json
a = [{
        "name": "jack",
        "date": "Jan-06-2021",
        "age": "24",
    },
    {
        "name": "jack1",
        "date": "Jan-07-2021",
        "age": "25",
    },
]
print(json.dumps(a))

b.py变成:

#!/usr/bin/env python3
import sys
import json
print(json.loads(sys.argv[1])[0])

你的剧本变成:

- hosts: all
  gather_facts: yes

  tasks:
    - command: /test-repo/test_python/a.py
      register: result

    - debug: 
        var: result.stdout
    
    - command: /test-repo/test_python/b.py '{{ result.stdout }}'
      register: result

    - debug: 
        var: result.stdout

所有这些都产生了回顾:

PLAY [all] **********************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************
ok: [localhost]

TASK [command] ******************************************************************************************************
changed: [localhost]

TASK [debug] ********************************************************************************************************
ok: [localhost] => {
    "result.stdout": [
        {
            "age": "24",
            "date": "Jan-06-2021",
            "name": "jack"
        },
        {
            "age": "25",
            "date": "Jan-07-2021",
            "name": "jack1"
        }
    ]
}

TASK [command] ******************************************************************************************************
changed: [localhost]

TASK [debug] ********************************************************************************************************
ok: [localhost] => {
    "result.stdout": {
        "age": "24",
        "date": "Jan-06-2021",
        "name": "jack"
    }
}

PLAY RECAP **********************************************************************************************************
localhost                  : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

推荐阅读