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

如何将Python脚本生成的字符串输出到curl POST命令中?

解决方法:将Python脚本输出作为POST请求数据发送

首先得帮你理清之前两种尝试的问题所在:

  • 第一种命令里的 -d "@python-scirpt.py",是把脚本代码本身作为POST数据发送,而不是执行脚本后的输出结果,完全不符合需求;
  • 第二种命令的引号嵌套语法错误(单引号内部不能直接用单引号),而且只是把字符串python /home/scripts/python-script.py作为text的值,并没有执行脚本获取输出。

下面是几种可靠的实现方式:

方法一:通过Shell变量捕获输出后构造JSON

先把Python脚本的输出存到变量,再用变量构造合法的JSON数据发送:

# 1. 执行脚本并捕获输出到变量
user_text=$(python /home/scripts/python-script.py)
# 2. 发送POST请求,用转义双引号保证JSON格式正确
curl --insecure -i -X POST \
  -H 'Content-Type: application/json' \
  -d "{\"text\": \"$user_text\"}" \
  https://10.10.10.6/hooks/84kk9emcdigz8xta1bykiymn5e

如果脚本输出可能包含双引号、反斜杠等特殊字符,建议用printf生成更安全的JSON:

user_text=$(python /home/scripts/python-script.py)
json_data=$(printf '{"text": "%s"}' "$user_text")
curl --insecure -i -X POST \
  -H 'Content-Type: application/json' \
  -d "$json_data" \
  https://10.10.10.6/hooks/84kk9emcdigz8xta1bykiymn5e

方法二:直接在curl命令中嵌入脚本执行(命令替换)

用Shell的命令替换$(...)直接获取脚本输出,嵌入到JSON中:

curl --insecure -i -X POST \
  -H 'Content-Type: application/json' \
  -d "{\"text\": \"$(python /home/scripts/python-script.py)\"}" \
  https://10.10.10.6/hooks/84kk9emcdigz8xta1bykiymn5e

如果你的系统安装了jq工具,还可以用它自动处理特殊字符的转义,生成绝对合法的JSON:

curl --insecure -i -X POST \
  -H 'Content-Type: application/json' \
  -d "$(python /home/scripts/python-script.py | jq -R '{text: .}')" \
  https://10.10.10.6/hooks/84kk9emcdigz8xta1bykiymn5e

方法三:修改Python脚本直接输出JSON

更省心的方式是让Python脚本直接输出符合要求的JSON,再用curl发送:
修改你的Python脚本为:

users=['mark','john','steve']
text = ' '.join(users)  # 更简洁的写法,避免末尾多余空格
import json
print(json.dumps({"text": text}))

然后执行curl命令:

curl --insecure -i -X POST \
  -H 'Content-Type: application/json' \
  -d "$(python /home/scripts/python-script.py)" \
  https://10.10.10.6/hooks/84kk9emcdigz8xta1bykiymn5e

这种方式最可靠,因为Python的json.dumps会自动处理所有JSON格式要求的转义逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:25:12