通过管道将文本传输到 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 finish.")
而不是 stdin.read()
,但我总是打印提示。
有没有办法查看用户是否将文本通过管道传输到 python 中而不使用会阻塞的方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 sys.stdin.isatty 来检查脚本是否正在交互运行。例子:
You can use
sys.stdin.isatty
to check if the script is being run interactively. Example: