【问题标题】:Using bash echo command to input into a python one liner使用 bash echo 命令输入到 python one liner
【发布时间】:2014-03-03 16:48:29
【问题描述】:

我正在尝试使用 echo 将字符串输入到 Python 单行中,然后对字符串执行凯撒密码。

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

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

输出应该是:Hello Holly.

当我输入命令时,我得到了什么:

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

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

谢谢。

【问题讨论】:

  • 使用列表推导简单地将函数应用于列表中的每个项目而不关心结果列表是一个不好的习惯;为你的导师感到羞耻。请改用... | python -c 'import sys; print "".join(sys.stdin)'

标签: python bash echo stdin


【解决方案1】:

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

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

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

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

【讨论】:

  • 只是为了详细说明,使用 Python 3,OP 的实现将起作用:)
  • 现在看起来不错,但是您正在打印 list,而不是 OP 想要的纯文本。最干净的可能是' '.join 它或其他东西......
  • @JustinC -- 情况并非总是如此......这取决于你如何编译,等等。
  • bob@pbx:~ $ echo "Hello Holly." | python -c " import sys; print [line for line in sys.stdin]" File "", line 1 import sys;打印 [sys.stdin 中的每一行] ^ IndentationError: unexpected indent
  • @user3375720 确保您直接复制和粘贴。在 CentOS 6 上使用 Python 2.6 对我来说效果很好。看起来您在 python -cimport 之后的 " 之间有一个空格 - 这可能是导致 IndentationError 的原因。
【解决方案2】:

看起来你正在使用 python2 而你的 istructor 正在使用 python 3。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    • 2016-04-22
    • 2014-03-20
    • 2012-12-11
    • 2021-03-15
    • 1970-01-01
    • 2018-04-05
    相关资源
    最近更新 更多