将python脚本打印到终端而不作为stdou的一部分返回

2024-04-25 13:00:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个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,然后将其分配给我想要的特定值。


Tags: pyechoenv脚本bash终端示例内容
3条回答

从我的评论。。

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

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

然后输出

[~] ./foo.py
hi
[~] FIVE=$?
[~] echo $FIVE
5

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

你总是可以在bash中处理你的脚本输出

不知道为什么@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发送数据,但终端没有显示它。

相关问题 更多 >

    热门问题