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

如何在Python脚本中同时获取Pipe与Here String的输入内容?

如何同时获取管道和Here-String的输入内容

当你用echo foobar | python myscript.py <<< test123调用脚本时,shell会将**最后一个stdin重定向(here-string的test123)**作为脚本的标准输入,管道传递的foobar会被覆盖,所以你的脚本只能读到test123。下面是几种可行的解决方案:

方案1:将其中一个输入作为命令行参数传递

把其中一个内容作为脚本的命令行参数,另一个通过管道传递,实现分别获取:

脚本代码

import sys

# 读取命令行参数(对应test123)
arg_content = sys.argv[1] if len(sys.argv) >= 2 else ""
# 读取管道输入(对应foobar)
pipe_content = sys.stdin.read().strip()

print(f"管道输入内容: {pipe_content}")
print(f"命令行参数内容: {arg_content}")

调用命令

echo foobar | python myscript.py test123

方案2:使用额外的文件描述符传递输入

利用shell的文件描述符重定向,将其中一个输入传递到非标准文件描述符(比如fd 3),脚本中单独读取该fd的内容:

脚本代码

import sys

# 读取标准输入(管道的foobar)
stdin_content = sys.stdin.read().strip()

# 读取文件描述符3的内容(here-string的test123)
try:
    with open(3) as fd3:
        fd3_content = fd3.read().strip()
except OSError:
    fd3_content = ""

print(f"管道输入内容: {stdin_content}")
print(f"额外FD输入内容: {fd3_content}")

调用命令

echo foobar | python myscript.py 3<<< test123

方案3:合并两个输入到同一管道(需固定格式)

如果两个输入可以按顺序合并到管道中,脚本通过读取多行来区分内容:

脚本代码

import sys

# 读取所有非空行
input_lines = [line.strip() for line in sys.stdin if line.strip()]

if len(input_lines) >= 2:
    print(f"第一个输入内容: {input_lines[0]}")
    print(f"第二个输入内容: {input_lines[1]}")
else:
    print("输入内容不足")

调用命令

(echo foobar; echo test123) | python myscript.py

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:07:41