2012-08-23 3 views
2

python pexpect에서 oupt를 필터링하고 싶습니다. 예를 들어 아래 코드에서 날짜 만 인쇄하려고합니다.pexpect의 출력을 필터링하는 방법

#!/usr/bin/env python 
import pexpect,time 
p=pexpect.spawn('ssh [email protected]') 
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 

답변

2

before는 이전 expect 호출하기 때문에 모든 것을 제공 할 것입니다.

당신은 줄 바꿈에 출력을 나눌 수 있습니다 : 그것은 더 나은 것 그러나

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

대신 2 초 수면의 프롬프트를 기대하기 :

p.sendline('mypassword') 
p.expect('[#\$] ') 
p.sendline('date') 
+0

ecatmur을 : 그건 좋은 해결책이었다. 또한 프롬프트를 기다리는 솔루션을 지적 해 주셔서 감사합니다. – Arun

관련 문제