Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe text to Python script or prompt

Tags:

python

bash

I'm trying to write a very simple email script in python. It's basically a poor man's mutt. At work, we send a lot of data from servers around, and it would be much easier to send it directly from the server.

The part that I'm stuck on is dealing with the message. I want users to to be able to do the following:

$ cat message.txt | emailer.py [email protected]
$ tail -n 2000 /var/log/messages | emailer.py [email protected]

Both of those are easy enough. I can just sys.stdin.read() and get my data.

The problem that I'm having is that I also want to support a prompt for typing a message with the following usage:

emailer.py --attach-file /var/log/messages [email protected]

Enter Your message. Use ^D when finished.
>>   Steve,
>>   See the attached system log. See all those NFS errors around 2300 UTC today.
>>
>>   ^D

The trouble that I'm having is that if I try to sys.stdin.read(), and there's no data, then my program blocks until stdin gets data, but I can't print my prompt. I could take a safe approach and use raw_input("Enter Your message. Use ^D when finished.") instead of stdin.read(), but then I always print the prompt.

Is there a way to see if a user piped text into python without using a method that will block?

like image 229
fandingo Avatar asked May 16 '11 22:05

fandingo


1 Answers

You can use sys.stdin.isatty to check if the script is being run interactively. Example:

if sys.stdin.isatty():
    message = raw_input('Enter your message ')
else:
    message = sys.stdin.read()
like image 118
zeekay Avatar answered Nov 04 '22 00:11

zeekay