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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With