Get Python command line output when called from a

2019-08-10 17:30发布

问题:

This may be a super simple question. I am calling a Python script on an Lubuntu OS (Cubietruck) via a shell script. This is to automate the process on start up (I want to maintain this process). Is there a simple way to view the output from Python? At the moment the Python script runs in the background, with no terminal. I have some errors that need checking. The script is:

#!/bin/sh
python recordSound.py

Thanks in advance.

回答1:

The proper solution would probably use logging as proposed in a comment.

In the meantime, you have to redirect both the standard output and the standard error stream in order to capture the normal output as wall as any error reported by your script:

#!/bin/sh
python recordSound.py >> logfile.log 2&>1

See one of the many web pages on that topic to explore the various redirection available from a shell script.


In addition, if you need both login and live view on the console, use the tee standard command:

#!/bin/sh
python recordSound.py 2&>1 | tee logfile.log


回答2:

Call your script directly. Just like you call bash script with a shebang (#!) you can call your python script with a #!/bin/env python. Then all you need to do is giving executable permission via chmod +x yourscript.py and calling your script directly like an application. This way, you can see the error codes. Another way to do is using logger module, which is great to see tracebacks and debug info.



回答3:

A very easy way would to redirect output from your script to a file

#!/bin/sh
python recordSound.py >> logfile.log

See the docs on IO redirection



回答4:

I'm no bash expert, but I think this should work, as python prints on the standart output unless told otherwise :

#!/bin/sh
python recordSound.py >> /tmp/my_python_log.txt

will add lines each time python outputs stuff. Go to the path specified to read the result. If you want a live view, use pipes '|' to redirect the output.

Edit : for a live view, you can also use the "tail -f /tmp/my_python_log.txt" command on another terminal as the other solution is running, which will first print the last 10 lines or so in the file, then automatically add new lines added. I love this command, really handy to view activity on a small Apache server. You can even watch multiple logs at once !