I need to build a script to interact with output from app commands. I used pexpect as in the code below.
import pexpect
import re
import sys
def script():
p = pexpect.spawn(command, encoding='utf8')
p.logfile = sys.stdout
p.expect('Enter org code:')
p.sendline('0123r')
p.expect('The cost to maintain is $(d.d*)')
price = p.match.groups()
num = float(price[0])
if num > 100:
print("nnPrice is too high: ", price[0])
p.sendline('nr')
else:
print("nPrice is good: ", price[0])
p.expect('Do you want to continue? [y/n] (n):')
p.sendline('yr')
p.expect('Review:')
p.interact()
p.expect('Done')
p.sendline('nnSucceeded')
The first expect p.expect('Enter org code:')
worked well. However, I always faces issue with the second expect p.expect('The cost to maintain is $(d.d*)')
│ /root/scripts/r.py:18 in script
│
│ 15 │ │ except:
│ 16 │ │ │ print("Exception was thrown")
│ 17 │ │ │ print(str(p))
│ ❱ 18 │ │ price = p.match.groups()
│ 19 │ │ print(price)
│ 20 │ │ num = float(price[0])
│ 21 │ │ if num > 100:
AttributeError: 'NoneType' object has no attribute 'groups'
It seems that p.match.groups()
was empty because the expect couldn’t match anything.
If I run p.expect('The cost to maintain is $(d.d*)')
with output from echo (same text as output from application command), everything worked fine.
I suspect that spawn only send the first line output in uft8.
After p.sendline('0123r')
, the output became bytes array again.
Any idea to overcome this? Is there any other way to work with output command?
krago is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.