将文本传递给Python脚本或提示

10 投票
1 回答
8351 浏览
提问于 2025-04-16 17:46

我正在尝试用Python写一个非常简单的邮件脚本。这个脚本就像是一个简易版的mutt(一个邮件客户端)。在工作中,我们需要从服务器发送很多数据,如果能直接从服务器发送邮件,那就方便多了。

我现在遇到的问题是如何处理消息。我希望用户能够做到以下几点:

$ cat message.txt | emailer.py fandingo@example.com
$ tail -n 2000 /var/log/messages | emailer.py fandingo@example.com

这两点都比较简单。我可以直接用sys.stdin.read()来获取数据。

但我现在的问题是,我还想支持一个提示,让用户可以输入消息,使用方式如下:

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

我遇到的麻烦是,如果我尝试用sys.stdin.read(),而没有数据输入,那么我的程序就会停在那里,直到有数据输入进来,但我却无法显示我的提示信息。

我可以采取一种安全的做法,使用raw_input("请输入您的消息。完成后请按^D。")来代替stdin.read(),但这样的话我每次都会显示提示。

有没有办法在不使用会阻塞的方法的情况下,检查用户是否通过管道输入了文本?

1 个回答

18

你可以使用 sys.stdin.isatty 来检查这个脚本是否是在交互模式下运行的。举个例子:

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

撰写回答