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

Linux沙箱中Python管道执行脚本时sys.stdin读取异常的解决咨询

问题解决方法

你的问题核心是:同时用管道和here-document给python3进程提供输入时,here-document会覆盖进程的标准输入(stdin),导致python3把here-doc里的内容当成Python代码执行,而非让管道传入的脚本读取这些内容。以下是沙箱环境中可行的替代方案:

方案1:用-c参数传递脚本

直接把脚本作为python3 -c的命令行参数,python3会从参数中读取执行代码,here-document的内容则会成为脚本的sys.stdin:

python3 -c 'import sys ; print(f"python here {sys.stdin.read()}")' <<here
data here
here

方案2:利用文件描述符重定向

通过额外的文件描述符分离脚本输入和数据输入,让python3从指定fd读取脚本,同时保留stdin供脚本读取数据:

echo 'import sys ; print(f"python here {sys.stdin.read()}")' | python3 /dev/fd/3 3<&0 <<here
data here
here

原理:管道的脚本内容被重定向到文件描述符3,python3从/dev/fd/3读取执行脚本,而进程的stdin依然是here-document的内容,脚本里的sys.stdin.read()就能正确读取到数据。

方案3:使用进程替换(需bash支持)

利用bash的进程替换特性创建匿名管道传递脚本,python3从这个匿名管道读取脚本,stdin则留给here-document的数据:

python3 <(echo 'import sys ; print(f"python here {sys.stdin.read()}")') <<here
data here
here

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:40:55