How to read from stdin or from a file if no data is piped in Python?

后端 未结 6 869
我在风中等你
我在风中等你 2021-02-01 20:19

I have a CLI script and want it to read data from a file. It should be able to read it in two ways :

  • cat data.txt | ./my_script.py
  • ./my
6条回答
  •  难免孤独
    2021-02-01 20:44

    For unix/linux you can detect whether data is being piped in by looking at os.isatty(0)

    $ date | python -c "import os;print os.isatty(0)"
    False
    $ python -c "import os;print os.isatty(0)"
    True
    

    I'm not sure there is an equivalent for Windows.

    edit Ok, I tried it with python2.6 on windows XP

    C:\Python26>echo "hello" | python.exe -c "import os;print os.isatty(0)"  
    False
    
    C:\Python26> python.exe -c "import os;print os.isatty(0)"  
    True
    

    So maybe it it not all hopeless for windows

提交回复
热议问题