David D
David D

Reputation: 143

How can I keep a python script on a remote server running after closing out of SSH?

I've coded a stock trading bot in Python3. I have it hosted on a server (Ubuntu 18.10) that I use iTerm to SSH into. Wondering how to keep the script actively running so that when I exit out of my session it won't kill the active process.

Basically, I want to SSH into my server, start the script then close out and come back into it when the days over to stop the process.

Upvotes: 14

Views: 17405

Answers (4)

Anto
Anto

Reputation: 3896

I came here for finding nohup python3 script.py &

Right solution for this thread is screen OR tmux. :)

Upvotes: 0

Filip Młynarski
Filip Młynarski

Reputation: 3612

You could use nohup and add & at the end of your command to safely exit you session without killing original process. For example if your script name is script.py:

nohup python3 script.py &

Normally, when running a command using & and exiting the shell afterwards, the shell will terminate the sub-command with the hangup signal (kill -SIGHUP <pid>). This can be prevented using nohup, as it catches the signal and ignores it so that it never reaches the actual application.

Upvotes: 6

Walter Schweitzer
Walter Schweitzer

Reputation: 424

You can use screen

sudo apt-get install screen

screen 

./run-my-script

Ctrl-A then D to get out of your screen

From there you will be able to close out your ssh terminal. Come back later and run

screen -ls

screen -r $screen_running

The screen running is usually the first 5 digits you see after you've listed all the screens. You can see if you're script is still running or if you've added logging you can see where in the process you are.

Upvotes: 10

Andrew DeCotiis-Mauro
Andrew DeCotiis-Mauro

Reputation: 67

Using tmux is a good option. Alternatively you could run the command with an & at the end which lets it run in the background.

https://tmuxcheatsheet.com/

Upvotes: 1

Related Questions