문제

I have 3 files, a.py, b.sh, and text.txt. Their contents follow:

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

Files text.txt and b.sh are read-only and must not be changed. How does one quit less using pexpect from within a.py?

도움이 되었습니까?

해결책

Assuming you don't want to do anything with the data, just read the first screen of data from less and then issue the 'q'.

(EDIT: This needed a tweak to give 'read' a size so that it didn't wait for the default size or 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()

Here is the code I used for test:

~/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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top