运行 使用 Python 的 Popen 通过 SSH 使用 nohup 命令然后注销

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

我正在尝试使用此 answer 使用 subprocess.Popen 使用 nohup 发出长 运行ning 进程,然后退出连接。

从登录shell,如果我运行

$ nohup sleep 20 &
$ exit

我得到了预期的行为,即我可以在睡眠进程仍在 运行ning 时注销,然后重新连接以检查其状态。但是,如果我尝试通过 Python 执行相同的操作,似乎 exit 命令在睡眠时间结束之前不会执行。

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()

我错过了什么?

来自文档: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.

好的,我现在很确定:

关于通信():[...]等待进程终止 所以我猜你之前的解决方案更好。但是如果你在最后调用它 if 应该不是问题或者如果你不需要 stdin 或 stderr 作为输出就根本不调用它

但是根据这个:Whosebug Comment 如果您在 Popen 调用中设置 preexec_fn=os.setpgrp 它应该可以工作。