将Python脚本打印到终端而不作为标准输出的一部分返回

9
我正在尝试编写一个Python脚本,返回一个值,然后将该值传递给一个Bash脚本。问题在于,我想在Bash中返回一个单一的值,但是我希望在执行过程中在终端上打印出一些东西。
下面是一个示例脚本,我们称之为return5.py:
#! /usr/bin/env python
print "hi"
sys.stdout.write(str(5))

我希望您在命令行运行它时,能以这种方式执行:
~:five=`./return5.py`
hi
~:echo $five
5

但我得到的是:
~:five=`./return5.py`
~:echo $five
hi 5

换句话说,我不知道如何让Python脚本打印并清除stdout,然后将其分配给我想要的特定值。

我有点困惑——如果不是标准输出,那你认为终端是什么?如果你只需要它们在不同的行上,可以使用 import sys; sys.stdout.flush() - Adam Smith
@AndrewMedico,这是非标准的,因为强烈约定了0代表“一切正常”,非零代表错误情况。 - bgschiller
是的,我想要非标准的,就是0表示一切正常,而其他任何值都表示出错。 - Doon
@AdamSmith 当我说“终端”时,我指的是我的终端屏幕上打印出来的内容。当我说“stdout”时,我指的是当我输入x=`command` 时分配给x的内容。 - arwright3
顺便提一下,你应该使用引号:echo "$five" - tripleee
显示剩余2条评论
3个回答

10

我不确定 @yorodm 为什么建议不使用 stderr。在这种情况下,这是我能想到的最佳选项。

请注意,print 会自动添加换行符,但当您使用 sys.stderr.write 时,您需要自己包含一个带有 "\n" 的换行符。

#! /usr/bin/env python
import sys


sys.stderr.write("This is an important message,")
sys.stderr.write(" but I dont want it to be considered")
sys.stderr.write(" part of the output. \n")
sys.stderr.write("It will be printed to the screen.\n")

# The following will be output.
print 5

使用这个脚本的样子是这样的:

bash$ five=`./return5.py`
This is an important message, but I dont want it to be considered part of the output.
It will be printed to the screen.
bash$ echo $five
5

这是可行的,因为终端实际上向您展示了三个信息流:stdoutstdinstderr。`cmd` 语法表示“捕获此进程的stdout”,但它不会影响stderr的输出。这正是设计它的目的--用于传递有关错误、警告或进程内部情况的信息。

您可能没有意识到在终端中也会显示stdin,因为这只是您键入时显示出来的内容。但并不一定要这样。您可以想象在终端中键入内容时没有任何东西显示出来。事实上,当您输入密码时,就是这样的情况。您仍然将数据发送到stdin,但终端不会将其显示出来。


2

from my comment..

#!/usr/bin/env python
#foo.py 

import sys
print "hi"
sys.exit(5)

然后是输出。
[~] ./foo.py
hi
[~] FIVE=$?
[~] echo $FIVE
5

0

你可以使用stdout输出你的信息,使用stderr在bash中捕获值。不幸的是,这是一些奇怪的行为,因为stderr旨在用于程序通信错误消息,所以我强烈建议你不要这样做。

另一方面,你总是可以在bash中处理你的脚本输出。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接