2011-05-16 46 views
10

我正在尝试在python中编写一个非常简单的电子邮件脚本。它基本上是一个穷人的笨蛋。在工作中,我们从服务器周围发送大量数据,并且从服务器直接发送它会容易得多。管道文本到Python脚本或提示

我卡在的部分是处理消息。我希望用户能够做到以下几点:

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

这两个都很简单。我只需sys.stdin.read()并获取我的数据。

说我有问题是,我也想支持一个提示与以下用法键入消息:

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 

说我有麻烦的是,如果我试图sys.stdin.read() ,并且没有数据,那么我的程序将阻塞,直到stdin获取数据,但我无法打印我的提示。 我可以采取安全的做法,并使用raw_input("Enter Your message. Use ^D when finished.")而不是stdin.read(),但我总是打印提示。

有没有办法查看用户是否将文本导入python而不使用会阻塞的方法?

+2

你见过'mail'命令吗? – csl 2011-05-16 22:28:22

+0

我们将主要使用它来附加文件。没有uuencode的邮件是没用的,我们没有。 – fandingo 2011-05-16 22:31:19

回答

17

您可以使用sys.stdin.isatty来检查脚本是否以交互方式运行。例如:

if sys.stdin.isatty(): 
    message = raw_input('Enter your message ') 
else: 
    message = sys.stdin.read() 
+0

谢谢zeekay。就像我认为的那样简单。 – fandingo 2011-05-16 23:00:15