让 python 脚本打印到终端而不作为标准输出的一部分返回 [英] getting python script to print to terminal without returning as part of stdout

查看:37
本文介绍了让 python 脚本打印到终端而不作为标准输出的一部分返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 python 脚本,该脚本返回一个值,然后我可以将其传递给 bash 脚本.问题是我想在 bash 中返回一个单一的值,但我想在此过程中将一些内容打印到终端.

I'm trying to write a python script that returns a value which I can then pass in to a bash script. Thing is that I want a singe value returned in bash, but I want a few things printed to the terminal along the way.

这是一个示例脚本.我们称之为 return5.py:

Here is an example script. Let's call it return5.py:

#! /usr/bin/env python
print "hi"
sys.stdout.write(str(5))

我想要的是当我从命令行运行它时以这种方式执行:

what I want is to have this perform this way when I run it from the command line:

~:five=`./return5.py`
hi
~:echo $five
5

但我得到的是:

~:five=`./return5.py`
~:echo $five
hi 5

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

In other words I don't know how to have a python script print and clear the stdout, then assign it to the specific value I want.

推荐答案

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

Not sure why @yorodm suggests not to use stderr. That's the best option I can think of in this case.

注意print会自动添加换行符,但是当你使用sys.stderr.write时,你需要自己加上一个"\n".

Notice that print will add a newline automatically, but when you use sys.stderr.write, you need to include one yourself with a "\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

使用这个脚本看起来像这样:

Using this script looks like this:

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 发生的事情.这完全是为了您使用它的目的而设计的 - 传达有关错误、警告或进程内部发生的情况的信息.

This works because the terminal is really showing you three streams of information : stdout, stdin and stderr. The `cmd` syntax says "capture the stdout from this process", but it doesn't affect what happens to stderr. This was designed exactly for the purpose you're using it for -- communicating information about errors, warnings or what's going on inside the process.

您可能没有意识到 stdin 也显示在终端中,因为它只是您键入时显示的内容.但也不必如此.您可以想象在终端中输入内容并没有显示任何内容.事实上,这正是您输入密码时发生的情况.您仍在向 stdin 发送数据,但终端并未显示数据.

You may not have realized that stdin is also displayed in the terminal, because it's just what shows up when you type. But it wouldn't have to be that way. You could imagine typing into the terminal and having nothing show up. In fact, this is exactly what happens when you type in a password. You're still sending data to stdin, but the terminal is not displaying it.

这篇关于让 python 脚本打印到终端而不作为标准输出的一部分返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆