You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible playbook中使用虚拟环境运行Python脚本

实现方案

你可以直接在ansible playbook中通过shell模块将虚拟环境激活和screen启动命令合并执行(ansible的每个task默认会开启独立shell会话,分开写激活命令不会生效),完整playbook示例如下:

---
- name: 后台运行虚拟环境中的Python脚本
  hosts: your_target_hosts # 替换为你的目标主机组/主机IP
  gather_facts: no

  tasks:
    # 可选:如果目标主机没装screen先安装,Debian/Ubuntu系用下面这个task
    - name: 安装screen
      apt:
        name: screen
        state: present
      become: yes
      # RHEL/CentOS系把上面的apt换成yum即可

    - name: 激活虚拟环境并后台运行test.py
      shell: |
        source /path/to/venv/bin/activate # 替换为你的虚拟环境实际绝对路径
        screen -dm python3 /path/to/test.py # 替换为test.py的实际绝对路径
      args:
        executable: /bin/bash # 明确指定用bash执行,避免默认sh不支持source的问题

注意事项

  • 所有路径建议写绝对路径,避免因ansible执行时的工作目录不匹配导致文件找不到
  • 若需要给screen会话指定别名方便后续管理,可以将启动命令改为 screen -dmS py_test_task python3 /path/to/test.py,后续在目标主机执行screen -r py_test_task即可进入会话查看运行状态
  • 如果脚本有输出日志的需求,建议在启动命令中追加日志输出路径,比如python3 test.py >> /var/log/test_py.log 2>&1方便排查问题

内容的提问来源于stack exchange,提问作者Alexander Vedmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 15:36:01