Skip to content
Advertisement

How do I bring a Python script’s output to foreground/background in Linux?

I’m running a Python script on AWS (Amazon Linux AMI). The script is meant to run 24/7 and prints out to the interpreter or command terminal.

It’s still in development, so I like to check to see how it’s behaving or if it’s stopped due to an error. But, I want to be able to close my ssh connection or turn off my local machine without interrupting the script, and then ssh back in and see it in real-time.

First I used:

[me@aws-x.x.x.x dir]$ nohup python3 myscript.py &

That worked fine for closing the ssh connection, coming back in, and seeing that it was still running, and then writing all the print statements to nohup.out.

Is there a way for me to bring this to the foreground and see the print statements in real-time, and then send it back to the background to disconnect from ssh without interrupting the program?

The code has the general form:

import time

count = 0

while count < 100000:
    print('Im working!')
    time.sleep(10)
    count += 1

print('All finished')

Advertisement

Answer

You can use tmux or screen (depending on which is available on the system) to run your program in a terminal multiplexer, detach from it and close the connection. When you return, you can attach to the same session and see your program running.

For tmux

$ tmux

# run your program in the tmux shell:
$ python3 myscript.py

Detach from the tmux session with Ctrl + b and then d

You can now safely exit your ssh session

Next time you log in, just tmux attach and you can see you script running.

Addition: For screen the detach command is Ctrl + a and d, reattaching is done with screen -r.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement