Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
pexpect startup help
#1
Hello ,
as I understand using pexpect will help me run a "program" inside python
for example run bluetoothctl in pi and run command insdie this interface.

so I want to start from start and understadn the command
this is what I did :
import pexpect
def Enterbluetooth():
    child = pexpect.spawn('bluetoothctl') ## the command I want to run - enter bluetoothctl interface
    pexpect.TIMEOUT(20) 
    print (child.read()) ## print the output of the command as is
    child.expect(pexpect.EOF)
    
if __name__ == '__main__':
    Enterbluetooth()
but I'm getting this error after ~30 seconds , why?
python3 pexpect_example.py
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pexpect/expect.py", line 111, in expect_loop
    incoming = spawn.read_nonblocking(spawn.maxread, timeout)
  File "/usr/lib/python3/dist-packages/pexpect/pty_spawn.py", line 482, in read_nonbloc                            king
    raise TIMEOUT('Timeout exceeded.')
pexpect.exceptions.TIMEOUT: Timeout exceeded.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "pexpect_example.py", line 10, in <module>
    Checkbluetooth()
  File "pexpect_example.py", line 5, in Checkbluetooth
    print (child.read()) ## print the output of the command as is
  File "/usr/lib/python3/dist-packages/pexpect/spawnbase.py", line 441, in read
    self.expect(self.delimiter)
  File "/usr/lib/python3/dist-packages/pexpect/spawnbase.py", line 341, in expect
    timeout, searchwindowsize, async_)
  File "/usr/lib/python3/dist-packages/pexpect/spawnbase.py", line 369, in expect_list
    return exp.expect_loop(timeout)
  File "/usr/lib/python3/dist-packages/pexpect/expect.py", line 119, in expect_loop
    return self.timeout(e)
  File "/usr/lib/python3/dist-packages/pexpect/expect.py", line 82, in timeout
    raise TIMEOUT(msg)
pexpect.exceptions.TIMEOUT: Timeout exceeded.
<pexpect.pty_spawn.spawn object at 0xb66d9e50>
command: /usr/bin/bluetoothctl
args: ['/usr/bin/bluetoothctl']
buffer (last 100 chars): b'Agent registered\r\n\x1b[0;94m[bluetooth]\x1b[0m# '
before (last 100 chars): b'Agent registered\r\n\x1b[0;94m[bluetooth]\x1b[0m# '
after: <class 'pexpect.exceptions.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 24722
child_fd: 5
closed: False
timeout: 30
delimiter: <class 'pexpect.exceptions.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
searcher: searcher_re:
    0: EOF
I gave 20 seconds timeout , so why I got error \ except and got out the code?
what did I do wrong?

where do I tell him that if nothing for 20 seconds - print "error in bluetooth" ad close exit the code or something ?

*** I have many more question , but let start from this :-)
Reply
#2
The documentation has some good examples: https://pexpect.readthedocs.io/en/stable/
there are also several tutorials which you can find with google.
Reply
#3
I read the manual before asking
but I found the answer somewhere else
this is the structure that works: (maybe it will help other)
    try:
        child = pexpect.spawn('bluetoothctl') ## write the command you want to run
        print( str(child)
    
    except pexpect.TIMEOUT:
        print('this is timeout error')
    except pexpect.EOF:
        print ('this is EOF error')
    except Exception as e:
        print(e)
now I'm trying to go to the next stage
when I run the bluetoothctl command on the cmd and someone connect to the pi I'm getting this :
pi@raspberrypi:~ $ bluetoothctl
Agent registered
[NEW] Device AA:A6:99:B5:F4:12
now I mane to get until the [NEW] - but how do I print it? I want to see the all line the code is reading

import pexpect
import time

def checkbluetooth():
    #while True:
        try:
            child = pexpect.spawn('bluetoothctl') ## write the command you want to run
            #print (child.read()) ## print the output of the command as is
            reply  = child.expect(['A','Ag']) ## to check if I get Agent register
            if (reply == 1):
                print( 'yes I got an a') ## I don;t think I need this
            if (reply == 0): ## the reply  is correct ?
                print (' GOT Anent   - can continue now ')
                print (child.before) ## why I don't see the line?
                replay = child.expect('[NEW]') ## meaning new device is trying to connect
                print ('got new device?')
                print (str(child)) ## why I don't see the line? [NEW] Device DC:A6:32:75:54:15 myblue
            else:
                pass
           

        except pexpect.TIMEOUT:
            print('this is timeout error')
        except pexpect.EOF:
            print ('this is EOF error')
        except KeyboardInterrupt:
            print ('Turn off app')
            child.close()
        except Exception as e:
            print(e)


if __name__ == '__main__':
    checkbluetooth()
this is my output
pi@raspberrypi:~ $ python3 pexpect_example.py
 GOT Anent   - can continue now
b''
got new device?
<pexpect.pty_spawn.spawn object at 0xb6743bd0>
command: /usr/bin/bluetoothctl
args: ['/usr/bin/bluetoothctl']
buffer (last 100 chars): b'EW\x1b[0m] Device AA:A6:99:B5:F4:12 \xd7\x91\xd7\x93\            xd7\x99\xd7\xa7\xd7\x94_274'
before (last 100 chars): b'gent registered\r\n\x1b[0;94m[bluetooth]\x1b[0m# \r\x            1b[K[\x1b[0;92m'
after: b'N'
match: <re.Match object; span=(53, 54), match=b'N'>
match_index: 0
exitstatus: None
flag_eof: False
pid: 26088
child_fd: 5
closed: False
timeout: 30
delimiter: <class 'pexpect.exceptions.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
Thanks ,
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reading and storing a line of output from pexpect child eagerissac 1 4,217 Feb-20-2024, 05:51 AM
Last Post: ayoshittu
  Using Autostart to run a GUI program at startup. Rpi Edward_ 1 617 Oct-28-2023, 03:19 PM
Last Post: SpongeB0B
  Use pexpect to send user input alisha17 0 1,886 May-10-2022, 02:44 AM
Last Post: alisha17
  Not able to read the text using pexpect/expect Bipinjohnson 7 4,024 Jan-10-2022, 11:21 AM
Last Post: Bipinjohnson
  Sudden Problem with pexpect gw1500se 3 2,381 Nov-19-2021, 11:21 PM
Last Post: bowlofred
  How to use pexpect in python? tiho_bg 1 1,521 Oct-30-2021, 02:50 PM
Last Post: Yoriz
  how to startup canbus interface on pi korenron 2 2,214 Oct-24-2021, 09:51 PM
Last Post: DeaD_EyE
  Pexpect timesout before executing whole output eagerissac 0 1,481 Jun-23-2021, 03:30 AM
Last Post: eagerissac
  Problem with pexpect.exception.TimeOUT korenron 0 3,287 Apr-12-2021, 03:25 PM
Last Post: korenron
  Error when running script on startup in Linux NoahTheNerd 0 1,947 Mar-07-2021, 04:54 PM
Last Post: NoahTheNerd

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020