首页 > 解决方案 > 在ansible中使用shell运行python脚本,但似乎无法使用print()输出stdout

问题描述

  shell: sleep 5; nohup python /tmp/rsync.py {{check}} {{source}} {{destination}} {{dest_host}} &
  register: status
  failed_when: "'FAILED' in status.stdout"

我的剧本有类似上面的代码片段。在 python 脚本中,我使用了 print 语句。但是当我运行和使用调试标准输出是空的。对于调试,我尝试了这两种方法 -

          - name: debug
            debug: var=status.stdout_lines
        - name: debug
          debug: msg={{ status.stdout }}

为了打印到标准输出,我还使用了sys.stdout.write. 即使这似乎不起作用。实现了我需要的一切。只有这行不通。
编辑:我必须在后台运行它。有没有新的方法来处理这个?

标签: pythonansible

解决方案


使用 Ansible [1]的异步支持

根据你的 shell 命令执行的时间调整 async 的值(如果是 5 秒,使 async 略高于 5)

根据您希望检查 shell 是否完成执行的频率调整 poll 的值

- name: Execute shell
  shell: sleep 5; nohup python /tmp/rsync.py {{check}} {{source}} {{destination}} {{dest_host}}
  async: 100
  poll: 1
  register: status
  failed_when: "'FAILED' in status.stdout"

推荐阅读