英文:
Pexpect script gives "None" for output
问题
以下脚本在服务器上运行时打印出None
:
#!/usr/bin/env python
import pexpect
import sys
dcommand = ('ls')
child = pexpect.spawn(dcommand)
output = child.before
print output
不确定为什么会这样 - 下面是手动运行ls时发生的情况 - 显然有文件!
[root@dub-svrfarm27 ~]# python script.py
None
[root@dub-svrfarm27 ~]# ls
anaconda-ks.cfg auto_ovirt_st_setup.py install_time kickstart-post.log original-ks.cfg script.py
有什么想法吗?我确定这是一些愚蠢的东西,但是什么...
英文:
The below script prints None
when ran on the server
#!/usr/bin/env python
import pexpect
import sys
dcommand = ('ls')
child = pexpect.spawn(dcommand)
output = child.before
print output
Not sure why this is - here is a comparison of what happens when i run ls manually - there's definitely stuff there!
<!-- language: lang-none -->
[root@dub-svrfarm27 ~]# python script.py
None
[root@dub-svrfarm27 ~]# ls
anaconda-ks.cfg auto_ovirt_st_setup.py install_time kickstart-post.log original-ks.cfg script.py
Any ideas? I'm sure its something silly, but what...
答案1
得分: 1
你需要期望prompt
,然后为每个操作从缓冲区读取数据,如下所示:
(pilenv) bash-5.0$ cat ll.py
import pexpect
import sys
dcommand = 'ls'
child = pexpect.spawn(dcommand)
child.expect(r'.*$') # my prompt ends with $, if yours ends with something else, then use that
print(child.readline())
(pilenv) bash-5.0$ python ll.py
b'agust.py\t IMG-20191213-WA0000.jpg lib l.py\r\n'
(pilenv) bash-5.0$
另外,请参考 code 以了解如何在个人项目中使用pexpect
的正确方法
英文:
You need to expect the prompt
and then read the data from the buffer for each operation like,
(pilenv) bash-5.0$ cat ll.py
import pexpect
import sys
dcommand = 'ls'
child = pexpect.spawn(dcommand)
child.expect(r'.*$') # my prompt ends with $, if yours ends with something else, then use that
print(child.readline())
(pilenv) bash-5.0$ python ll.py
b'agust.py\t IMG-20191213-WA0000.jpg lib l.py\r\n'
(pilenv) bash-5.0$
Also please refer the code for a sane way to use pexpect
which i did for something personal
答案2
得分: 0
#!/usr/bin/env python
import pexpect
import sys
dcommand = ('ls')
child = pexpect.spawn(dcommand)
child.expect(pexpect.EOF)
output = child.before
print(output)
英文:
#!/usr/bin/env python
import pexpect
import sys
dcommand = ('ls')
child = pexpect.spawn(dcommand)
child.expect(pexpect.EOF)
output = child.before
print(output)
you need to add child.expect(pexpect.EOF)
you can find more information at https://pexpect.readthedocs.io/en/stable/api/pexpect.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论