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

如何用Python单行代码按行读标准输入及实现Unix管道命令等价写法?

Python单行处理标准输入相关问题解答

1. 单行代码按行读取标准输入

以下是几种实用的单行写法:

  • 直接遍历sys.stdin处理每行:
    python -c "import sys; for line in sys.stdin: print(line.rstrip())"
    
    用rstrip()是为了移除每行末尾的换行符,避免输出时出现重复换行。
  • 用列表推导式一次性收集所有行后输出:
    python -c "import sys; lines = [line.rstrip() for line in sys.stdin]; print('\n'.join(lines))"
    
  • 借助fileinput模块(无需手动处理sys.stdin):
    python -c "import fileinput; for line in fileinput.input(): print(line.rstrip())"
    

2. Unix命令ls | perl -ne 'print "test $_"'的Python等价写法

原Perl命令的作用是读取标准输入的每一行,在每行内容前拼接test 后输出。对应的Python单行写法如下:

  • 基础遍历版:
    ls | python -c "import sys; for line in sys.stdin: print(f'test {line.rstrip()}')"
    
  • 生成器表达式简化版:
    ls | python -c "import sys; print('\n'.join(f'test {line.rstrip()}' for line in sys.stdin))"
    
  • 用fileinput的版本:
    ls | python -c "import fileinput; print('\n'.join(f'test {line.rstrip()}' for line in fileinput.input()))"
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 20:12:33