如何使远程执行的 pexpect spawn 在继续之前完全等待命令解决?

How to make remotely executed pexpect spawn FULLY WAIT for a command to resolve before continuing?

我正在使用 pexpect 连接到远程计算机 运行ning QNX,上传一个可执行文件,运行 可执行文件,然后将结果返回到我的本地计算机。

我的问题是:命令执行得很好,但我丢失了所有记录的结果,因为一旦我对 运行 我的应用程序执行命令,进程 return 就会给我(让我们称之为 ./application),一个 C++ 可执行文件。我需要做的是让进程等到命令完全完成 运行ning 后再继续。

我试过使用 proc.wait() 无济于事,我最好的猜测是因为 proc 是 SSH 会话,而不是 运行ning ./application 启动的进程。我试过 proc.expect("bash-username$") 和类似的,只是发现应用程序 returns 立即仍然存在。

代码相当简单明了,但并不完全符合我的期望。这是我如何进行操作的示例:

// This section all works fine.  Establish SSH and expect Last Login info

ssh_cmd = ssh_cmd = "ssh " + self.user + "@" + self.hostname
self.proc = pexpect.spawn(ssh_cmd)
self.proc.expect("Last login", timeout = 5)
print("SSH login successful!")
self.is_connected = True

// Problems are here.  Outside scope executes a command now by calling this:
// Let's say the command here is Sleep 5.  Or an executable ./application  
//The Pexpect below SHOULD wait until it finishes executing, but it 
doesn't Sleep for 5 seconds or wait for ./application, this expect 
line returns IMMEDIATELY every time. 

def execute_command(self, command):
    if self._is_connected:
        self.proc.sendline("command")
        self.proc.expect("username:/")

所以基本上每次运行s,它在函数执行命令后立即继续下一部分代码,似乎不关心proc.expect。我是否错误地使用了它?我怎样才能让进程等到命令实际执行完毕,而不是立即发送行和 return?

我找到了解决我自己问题的方法,使用 subprocess 模块而不是 pexpect。

解决方案是使用命令变量为 SSH 调用 subprocess.Popen,如下所示:

command_as_string = '/home/user/applicationExecutable'
ssh = subprocess.Popen(['ssh', '-t', 'username@hostname',
                        command_as_string'],
                                   stderr=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   shell=False,
                                   universal_newlines=True,
                                   bufsize=0
                                   )

它将等到命令解决后再断开连接并按预期继续 Python 文件的其余部分。