2

python pexpect で、出力をフィルタリングしたい。たとえば、以下のコードでは、日付のみを印刷したいと考えています。

#!/usr/bin/env python
import pexpect,time
p=pexpect.spawn('ssh myusername@192.168.151.80')
p.expect('Password:')
p.sendline('mypassword')
time.sleep(2)
p.sendline('date')
p.expect('IST')
current_date = p.before
print 'the current date in remote server is: %s' % current_date 

実際の出力:

the current date in remote server is:
Last login: Thu Aug 23 22:58:02 2012 from solaris3
Sun Microsystems Inc.   SunOS 5.10      Generic January 2005
You have new mail.
welcome
-bash-3.00$ date
Thu Aug 23 23:03:10 

期待される出力:

the current date in remote server is: Thu Aug 23 23:03:10 
4

1 に答える 1

2

beforeexpect前回の呼び出し以降のすべてを提供します。

出力を改行で分割できます。

current_date = p.before.split('\n')[-1]

ただし、2 秒間スリープするのではなく、プロンプトが表示されることを期待する方がよいでしょう。

p.sendline('mypassword')
p.expect('[#\$] ')
p.sendline('date')
于 2012-08-24T09:02:28.523 に答える