I would like to save all the messages that my program displays through print , in this casemain.py
I had tried doing the following in my crearlog.sh
, and it works when I foreground the process with./crearlog.sh
#!/bin/bash
python main.py >> logextraccion.log
But when I run in the background with ./crearlog.sh &
the text is not saved in the log. Why is this happening and how do I fix it?
Add that I do not want to modify my program main.py
, but crearlog.sh
.
The reason I want to do it in the background is because I'm using an ssh connection to a remote server.
Hi, what you should do is, in addition to redirecting the standard output (stdout), redirect the standard error (stderr).
You can do this in various ways. One way is the one indicated in the comments of the question.
where
2>&1
you are telling standard error to go to standard output (sorry for the tongue twister) and the last one&
is because you want it to run in the background.A cleaner way is:
With
&>
you indicate that you are redirecting both outputs.If you wanted you could do the reverse, send
stdout
tostderr
(standard output to standard error).You do this like this (I put it as an example since it does not work for your case):
In this article you can see various forms of redirection.
In this case it is better to use
nohup
since among other things the execution will continue even if you have disconnected your session.This will launch the program in the background and all output will be stored in
nohup.out
To check if the program is running you can use
More information about
nohup
I recommend that if you work with connections via ssh to remote servers, apart from the solution provided, it is that you familiarize yourself with the screen program (or byobu ), it will allow you to disconnect and reconnect maintaining your user session and being able to resume things where they were. you left, especially with processes that last a long time and that a connection drop can cause the process to drop as well as your session.
The basic usage is very simple:
It will launch a new session, there you can launch your script. You press "Ctrl + a d", you disconnect from those sessions and you can close the ssh connection, to reconnect later, you access via ssh and you only have to write:
and voila.
Note: You can open as many screen sessions as you want, then -r will ask you to specify the one you want.