Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
772 views
in Technique[技术] by (71.8m points)

python, set terminal type in pexpect

I have a script which uses pexpect to start a CLI program. It works a bit like a shell where you get a prompt where you can enter some commands.

The problem I have, I think, is that this program uses a coloured prompt.

This is what I do

import pprint
import pexpect

1 a = pexpect.spawn('program')
2 a.expect("prompt>")
3 print "---------start------------"
4 print(a.before)
5 a.sendline("command")
6 a.expect("prompt>")
7 print "---------before------------"
8 pprint.pprint(a.before)
9 print "---------after------------"
10 pprint.pprint(a.after)

This is the output:

> python borken.py
---------start------------
A lot of text here from the enjoying programs start-up, lorem ipsum ...  
---------before------------
' x1b[0mx1b[8Dx1b[Kx1b[1mx1b[34m'
---------after------------
'prompt>'

For some reason the first prompt colour coding borkens up things and a.before at line 8 is garbled, normal print does not work, even if I see that the command at line 5 actually produced a lot of output.

Does someone know what the problem could be, or is it possible to set the terminal type in pexpect to avoid the colours?

I am using tcsh shell

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok, I found the answer. csl's answer set me on the right path.

pexpect has a "env" option which I thought I could use. like this:

a = pexpect.spawn('program', env = {"TERM": "dumb"})

But this spawns a new shell which does not work for me, our development environment depends on a lot of environmental variables :/

But if I do this before spawning a shell:

import os
os.environ["TERM"] = "dumb"

I change the current "TERM" and "dumb" does not support colours, which fixed my issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...