getting python script to print to terminal without returning as part of stdout
python, stdout
Solution
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.
Problem
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.