Skip to main content
 首页 » 编程设计

python之我如何使用 pexpect 在后台运行东西

2024年11月01日19sky-heaven

我正在脚本中使用 '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 做到这一点?

我的操作如下(仅供引用):

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

请您参考如下方法:

.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 key ,然后你就可以在没有密码的情况下做你想做的事,并且 pexpect 完全由 simply running scp .