日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python pexpect 模块

發布時間:2025/5/22 python 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python pexpect 模块 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Pexpect 模塊

兩個主要接口

pexpect.run('ls -la')

?

child = pexpect.spawn('scp foo myname@host.example.com:.')

? ? ? ? child.expect ('Password:')

? ? ? ? ##在這個地方會阻塞,直到出現password或者超時推出

? ? ? ? child.sendline (mypassword)

管道符的特殊處理

?

shell_cmd = 'ls -l | grep LOG > log_list.txt'

? ? ? ? ? ? ? ?child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])

? ? ? ? ? ? ? ?child.expect(pexpect.EOF) #等待斷開

將log日志重定向到某個文件或者標準輸出

fout = open('filename','w+')

child.logfile = fout

child.logfile = sys.stdout

fout.close()

如果是僅僅看child返回的信息,而不看你寫給child的信息,那么

child.logfile_read = sys.stdout

寫給child的信息則是

child.logfile_send = sys.stdout

?

? ? try:

? ? ? ? child.sendline('ls -l')

? ? ? ? child.expect(pexpect.EOF)

? ? ? ? #child.prompt()

? ? ? ? print child.before

? ? except:

expect不斷的讀入緩沖區內容等待匹配結束,before代表匹配前的內容,即ls的執行結果,after代表匹配之后的內容

child.before child.buffer? ? ? ? ? ? ? ? ? ?

?

  • try:?
  • ????index?=?pexpect?(['good',?'bad'])?
  • ????????if?index?==?0:?
  • ????????????do_something()?
  • ????????elif?index?==?1:?
  • ????????????do_something_else()?
  • ????except?EOF:?
  • ????????do_some_other_thing()?
  • except?TIMEOUT:?
  • ????do_something_completely_different()??
  • 另外在pexpect中,有一個很好用的接口,就是sendcontrol(),比如說sendcontrol('c'),向目標機器發送一個中斷符號,主要用在前面的命令執行時間過長,退出當前命令,并使當前命令對后續命令沒有影響,比如說expect('~#', 3),此時發生了超時,后續再發送命令,可能那個超時的命令的結果還將輸出,就會對當前的結果有影響,發送sendcontrol('c'),則好的多,再expect()一下就ok啦

    sendeof(),只能用在開頭處,另外對于某些平臺是發送ctrl+d命令,所以還是不是很好用

    參考文獻: http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect1/ http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect2/

    ?

    ?

    ?

    ?

    ?

    轉載于:https://blog.51cto.com/3502990/653254

    總結

    以上是生活随笔為你收集整理的python pexpect 模块的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。