如何使用 pexpect 从 unix 中的对话框中获取文本?
我这里有一个 shell 脚本,如下所示:
#!/bin/bash
CPUSELECTION="1 386SX off \
2 386DX on \
3 486SX off \
4 486DX off "
#dialog --backtitle "Select CPU" --radiolist "Select the cpu" 10 40 4 $CPUSELECTION
echo $CPUSELECTION
现在我的 py 文件是
import pexpect
child = pexpect.spawn ('sh /tmp/test.sh')
child.expect('386DX')
fp = open('/tmp/test.txt', 'w')
print >> fp, "Before 386DX:", child.before
print >> fp, "After 386DX:", child.after
child.expect('486SX')
print >> fp, "Before 486SX:", child.before
print >> fp, "After 486SX:", child.after
fp.close()
该脚本的输出是
$ cat /tmp/test.txt
Before 386DX: 1 386SX off 2
After 386DX: 386DX
Before 486SX: on 3
After 486SX: 486SX
从这里我将获取一些文本之间的文本。
但如果我使用对话框,
#!/bin/bash
CPUSELECTION="1 386SX off \
2 386DX on \
3 486SX off \
4 486DX off "
dialog --backtitle "Select CPU" --radiolist "Select the cpu" 10 40 4 $CPUSELECTION
#echo $CPUSELECTION
我会得到垃圾输出。
有没有办法从对话框中获取纯文本?
带对话框的 Shell 脚本是由第三方提供的,因此我们无法更改脚本:(。
请提供不更改 shell 脚本的解决方案。
I have a shell script script here as below:
#!/bin/bash
CPUSELECTION="1 386SX off \
2 386DX on \
3 486SX off \
4 486DX off "
#dialog --backtitle "Select CPU" --radiolist "Select the cpu" 10 40 4 $CPUSELECTION
echo $CPUSELECTION
now my py file is
import pexpect
child = pexpect.spawn ('sh /tmp/test.sh')
child.expect('386DX')
fp = open('/tmp/test.txt', 'w')
print >> fp, "Before 386DX:", child.before
print >> fp, "After 386DX:", child.after
child.expect('486SX')
print >> fp, "Before 486SX:", child.before
print >> fp, "After 486SX:", child.after
fp.close()
The output of this script is
$ cat /tmp/test.txt
Before 386DX: 1 386SX off 2
After 386DX: 386DX
Before 486SX: on 3
After 486SX: 486SX
From this I will get the text between some text.
But if I use dialog box
#!/bin/bash
CPUSELECTION="1 386SX off \
2 386DX on \
3 486SX off \
4 486DX off "
dialog --backtitle "Select CPU" --radiolist "Select the cpu" 10 40 4 $CPUSELECTION
#echo $CPUSELECTION
I got the junk output.
Is there any way to get the plain text from the dialog box?
Shell Script with dialog box is given by third party so we cant change the script :(.
Please provide the solution without changing shell script.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您看到的垃圾输出是 ANSI 转义码。你可以用这样的东西去掉它们:
然后,你可以使用
,你只会看到文本。它仍将包含对话框框架中的线条,但这对您来说应该更容易处理。
The junk output that you're seeing is ANSI escape codes. You can strip them out with something like this:
then, you can use
and you'll just see the text. It will still include the lines from the dialog frames, but that should be easier for you to handle.