[Tutor] A question about using stdin/out/err vs named files

Adam Jensen hanzer at riseup.net
Sun Oct 19 18:38:43 CEST 2014


On 10/18/2014 02:36 PM, George R Goffe wrote:
> Hi,
> 
> When you run a python program, it appears that stdin, stdout, and stderr are opened automatically.
> 
> I've been trying to find out how you tell if there's data in stdin (like when you pipe data to a python program) rather 
> than in a named input file. It seems like most/all the Unix/Linux 
> commands are able to figure this out. Do you know how Python programs do this or might do this?
> 
> MANY thanks for any/all help/hints/tips/suggestions,
> 
> George...

Command line argument parsing aside, perhaps something like this would
be useful:

script.py
-------------------------------------------
#!/usr/bin/env python3
import os, stat
mode = os.fstat(0).st_mode

if stat.S_ISFIFO(mode):
     print("stdin is a pipe")
elif stat.S_ISREG(mode):
     print("stdin is a redirected file")
elif stat.S_ISCHR(mode):
     print("stdin is terminal")
else:
     print("stdin is weird")
-------------------------------------------

$ ./script.py
stdin is terminal

$ cat script.py | ./script.py
stdin is a pipe

$ ./script.py < script.py
stdin is a redirected file



More information about the Tutor mailing list