开发者

Pipe text to Python script or prompt

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 fandingo@example.com
$ tail -n 2000 /var/log/messages | emailer.py fandingo@example.com

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 fandingo@example.com

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开发者_C百科 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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜