bash 使用bash echo命令输入python one liner

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22152412/
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 09:47:46  来源:igfitidea点击:

Using bash echo command to input into a python one liner

pythonbashechostdin

提问by Bob Glidewell

I am trying to input a string using echo into a Python one liner then perform a Caeasar's Cipher on the string.

我正在尝试使用 echo 将字符串输入到 Python one liner 中,然后对字符串执行 Caeasar 的密码。

One of the examples my instructor gave me was this.

我的老师给我的例子之一就是这个。

~ $ echo "Hello Holly." | python -c "import sys; [print(line) for line in sys.stdin]"

The output is suppose to be: Hello Holly.

输出假设为: Hello Holly.

How ever when I type the command in I get:

当我输入命令时,我得到:

File "<string>", line 1
 import sys; [print(line) for line in sys.stdin]
                  ^
SyntaxError: invalid syntax

I would appreciate it if someone could point out the error to me. I am using Python 2.6 on Centos 6.

如果有人能向我指出错误,我将不胜感激。我在 Centos 6 上使用 Python 2.6。

Thanks.

谢谢。

回答by MattDMo

In Python 2 printis a statement, not a function. Try this instead:

在 Python 2 中print是一个语句,而不是一个函数。试试这个:

echo "Hello Holly." | python -c "import sys; print [line for line in sys.stdin]"

Alternatively, you could use the following to just print plain text (thanks @mgilson):

或者,您可以使用以下内容仅打印纯文本(感谢@mgilson):

echo "Hello Holly." | python -c "import sys; print ' '.join([line for line in sys.stdin])"

回答by Cam

It looks like you are using python2 while your isntructor is using python 3.

看起来您使用的是 python2,而您的 istructor 使用的是 python 3。