Skip to main content
 首页 » 编程设计

python之Python 中的脚本和交互式终端客户端

2025年05月04日12傻小

我需要使用 Python 编写脚本/自动化交互式终端客户端。客户端接受三个参数并运行如下:

>./myclient <arg1> <arg2> <arg3> 
Welcome... 
blah... 
blah.. 
[user input] 
some more blah... blah... for the input entered 
blah..  
blah.. 
[basically it accepts input and puts the output in the console until the user types 'quit'] 

现在我需要在 Python 中自动执行此操作,并将控制台输出保存在文件中。

请您参考如下方法:

您可能想使用 pexpect (这是古老的 expect 的纯 python 版本)。

import pexpect 
proc = pexpect.spawn('./myclient <arg1> <arg2> <arg3>') 
proc.logfile = the_logfile_you_want_to_use 
proc.expect(['the string that tells you that myclient is waiting for input']) 
proc.sendline('line you want to send to myclient') 
proc.expect(['another line you want to wait for']) 
proc.sendline('quit') # for myclient to quit 
proc.expect([pexpect.EOF]) 

这样的事情应该足以解决您的问题。不过,pexpect 的功能更多,因此请阅读文档以了解更高级的用例。