使用Pexpect退出更少

时间:2013-06-25 18:28:29

标签: python bash python-2.7 pexpect

我有3个文件,a.pyb.shtext.txt。他们的内容如下:

a.py:

#!/usr/bin/env python
import os, pexpect

class zz:
    def __init__(self):
        child = pexpect.spawn ('/home/usr/Desktop/b.sh')

        ###  VVV     LINE IN QUESTION BELOW    VVV
        child.expect(pexpect.EOF)

        child.sendline('q')
        child.interact()

z = zz()

b.sh:

less /home/usr/Desktop/text.txt
echo 'all done'
sleep 3

的text.txt:

thisistext

文件text.txtb.sh是只读的,不得更改。如何在less内使用pexpect退出a.py

1 个答案:

答案 0 :(得分:1)

假设您不想对数据做任何事情,只需从less中读取第一个数据屏幕,然后发出' q'。

(编辑:这需要进行一次调整,以便'读取'大小,以便它不会等待默认大小或eof)

#!/usr/bin/env python
import os, pexpect

class zz:
    def __init__(self):
        child = pexpect.spawn ('/home/usr/Desktop/b.sh')
        # grab the first screen from 'less'
        child.read(1)
        child.send('q')

z = zz()

以下是我用于测试的代码:

~/tmp/reader$ cat a.py
#!/usr/bin/env python
import pexpect

try:
    open('status.txt', 'w')
    child = pexpect.spawn('/bin/sh "./b.sh"', timeout=10)
    child.send('q')
    child.expect(pexpect.EOF)
except Exception,e:
    print 'exception'
print open('status.txt').read()


~/tmp/reader$ cat text.txt
iamtext

~/tmp/reader$ cat b.sh
#!/bin/sh
less text.txt
echo 'all done'
sleep 3
date > status.txt