bash 管道文本到 Python 脚本或提示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6024149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:01:03  来源:igfitidea点击:

Pipe text to Python script or prompt

pythonbash

提问by fandingo

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.

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

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.

这两个都很容易。我可以直接sys.stdin.read()获取我的数据。

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.

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

Is there a way to see if a user piped text into python without using a method that will block?

有没有办法查看用户是否在不使用会阻塞的方法的情况下将文本通过管道传输到 python 中?

回答by zeekay

You can use sys.stdin.isattyto check if the script is being run interactively. Example:

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

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