getting python script to print to terminal without returning as part of stdout

旧时模样 提交于 2019-12-23 08:30:12

问题


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.

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

but what I get is:

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

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.


回答1:


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

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

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.

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.




回答2:


from my comment..

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

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

then the output

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



回答3:


You can use stdout to output your messages and stderr to capture the values in bash. Unfortunately this is some weird behaviour as stderr is intended for programs to communicate error messages so I strongly advice you against it.

OTOH you can always process your script output in bash



来源:https://stackoverflow.com/questions/23118252/getting-python-script-to-print-to-terminal-without-returning-as-part-of-stdout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!