Tuesday, January 30, 2024

[SOLVED] write out of a python program execute through bash

Issue

I have a little python tool useable in bash command, on a embedded linux (on a seismic digitizer). In my example, that's the tool which call the sensors (in this case, voltage sensors) then out the results in the terminal. The tool is just 3 lines of script that call a library:

#!/usr/bin/python
import sys
from ccube.apps.ccube_sensors import main
sys.exit(main())

I really don't know what is "ccube.apps.ccube_sensors". Nevermind, I just want the print result in bash to be inject in a txt file, but doing a ">" doesn't work.

Here the use of the tool :

/usr/bin/ccube-sensors voltage -m all > test.log

(-m is or "machine" format out, "all" is all sensors)

in the terminal, it produce :

system=12.60V battery=3.25V

But test.log still empty. Notice : the digitizer run a old 2.7 python and this is a arm proc device with a unknow embedded linux.


Solution

The issue is that your Python abuses the sys.exit() function to print its output. As a result, it prints the string it receives as a parameter on stderr and exits with a non-successful error status. As a result of writing on stderr, rather than stdout, the messages are not redirected by your > test.log at the end of your command.

In order to leave the Python unchanged, you would need to redirect stderr as follows - note the 2 denoting stderr:

/usr/bin/ccube-sensors voltage -m all 2> test.log

But the better solution, IMHO, is to change your Python to stop abusing sys.exit() and use the regular print() function, then your original bash script will work:

#!/usr/bin/python
from ccube.apps.ccube_sensors import main
print main()

I don't know Python 2.7, but I believe that's how print() used to work.



Answered By - Mark Setchell
Answer Checked By - Dawn Plyler (WPSolving Volunteer)