title: How to read from stdin or from a file if no data is piped in Python?
body: <p>I have a CLI script and want it to read data from a file. It should be able to read it in two ways :</p>
  
  <ul>
  <li><code>cat data.txt | ./my_script.py</code></li>
  <li><code>./my_script.py data.txt</code></li>
  </ul>
  
  <p>—a bit like <code>grep</code>, for example.</p>
  
  <p>What I know:</p>
  
  <ul>
  <li><code>sys.argv</code> and <code>optparse</code> let me read any args and options easily.</li>
  <li><code>sys.stdin</code> let me read data piped in</li>
  <li><code>fileinput</code> make the full process automatic</li>
  </ul>
  
  <p>Unfortunately:</p>
  
  <ul>
  <li>using <code>fileinput</code> uses stdin and any args as input. So I can't use options that are not filenames as it tries to open them.</li>
  <li><code>sys.stdin.readlines()</code> works fine, but if I don't pipe any data, it hangs until I enter <kbd>Ctrl + D</kbd></li>
  <li>I don't know how to implement "if nothing in stdin, read from a file in args" because <code>stdin</code> is always <code>True</code> in a boolean context.</li>
  </ul>
  
  <p>I'd like a portable way to do this if possible. </p>