V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
rockyaow
V2EX  ›  Python

stdin 如何能自动判断

  •  
  •   rockyaow · 2014-07-29 18:41:17 +08:00 · 2897 次点击
    这是一个创建于 3559 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我写了个脚本,想支持用Linux 管道(|)方式传参数进去

    但是如果直接用sys.stdin.read去读,程序就卡住了,显然这个方法是不正确的。

    怎么能自动判断调用脚本的时候是否使用了管道?从而再去读stdin呢?
    4 条回复    2014-07-30 10:15:18 +08:00
    qq529633582
        1
    qq529633582  
       2014-07-29 19:10:53 +08:00   ❤️ 1
    isTTY()
    heiher
        2
    heiher  
       2014-07-29 23:20:43 +08:00 via iPhone
    可以要求参数为-的时候读stdin,如 vim a.txt 访问文件,而 vim - 就访问 stdin。
    bombless
        3
    bombless  
       2014-07-30 08:59:50 +08:00
    同意@heiher 的。
    判断是不是管道比较像Windows风格而不是*nix
    rockyaow
        4
    rockyaow  
    OP
       2014-07-30 10:15:18 +08:00
    谢谢各位,sys.stdin.isatty 确认可行
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2869 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:38 · PVG 22:38 · LAX 07:38 · JFK 10:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.