如何使用pexpect在后台运行内容?

时间:2019-08-14 11:12:18

标签: python ssh pexpect

我正在脚本中使用'Pexpect'库,并希望在此之后进行一些操作。我正在做的事情如下:

def child():
        pexpect.spawn("ssh tranzmeo@192.168.21.110")
        child.expect(".*password.*")
        child.sendline('tranzmeo1@#')
        print(child.before)
        child.interact()
        return

这是我从另一个文件(称为训练)中调用的函数。运行训练时,会调用child(),但会立即停止程序并进入tranzmeo控制台,我不要我需要ssh并在tranzmeo中在后台进行一些操作。如何使用pexpect做到这一点?

我的operation如下(仅供参考):

def scp(tensorflow_file_location_temp ,tensorflow_file_loc)
        child = pexpect.spawn("scp -r " + tensorflow_file_location_temp + "models@192.168.21.117:" + tensorflow_file_location )
        child.expect(".*password.*")
        child.sendline('Tranzmeo1@#')
        child.interact()

1 个答案:

答案 0 :(得分:1)

.interact() gives control of the child process to the interactive user (the human at the keyboard). Keystrokes are sent to the child process, and the stdout and stderr output of the child process is printed.

如果您不想那样,就不要称呼它!您想继续处理从pexpect.spawn("ssh tranzmeo@192.168.21.110")返回的对象(您发布的代码并未将其分配给child,我认为这是复制粘贴错误):

child.sendline("scp -r " + tensorflow_file_location_temp + "models@192.168.21.117:" + tensorflow_file_location)

但是您应该设置ssh密钥,然后您就可以在没有密码的情况下进行所需的操作,并且simply running scp可以完全pexpect