Pietro Marchesi
Pietro Marchesi

Reputation: 882

Running a nohup command through SSH with Python's Popen then logging out

I'm trying to use this answer to issue a long-running process with nohup using subprocess.Popen, then exit the connection.

From the login shell, if I run

$ nohup sleep 20 &
$ exit

I get the expected behavior, namely that I can log out while the sleep process is still running, and connect back later to check on its status. If I try to the same through Python, however, it seems as though the exit command does not get executed until the sleeping time is over.

import subprocess

HOST=<host>
sshProcess = subprocess.Popen(['ssh', HOST],
                                stdin = subprocess.PIPE,
                                stdout = subprocess.PIPE,
                                universal_newlines = True,
                                bufsize = 0)
sshProcess.stdin.write("nohup sleep 20 &\n")
sshProcess.stdin.write("exit\n")
sshProcess.stdin.close()

What am I missing?

Upvotes: 1

Views: 1501

Answers (1)

ShuzZzle
ShuzZzle

Reputation: 302

From the docs: Python Docs

Warning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

Alright pretty sure i got it now:

About communicate(): [...]Wait for process to terminate So i guess your earlier Solution was better. But if you call it at the end if shouldn't be a problem or just don't call it at all if you don't need stdin or stderr as output

However according to this:StackOverflow Comment If you set preexec_fn=os.setpgrp in your Popen call it should work.

Upvotes: 1

Related Questions