Pexpect脚本返回输出为“None”。

huangapple go评论75阅读模式
英文:

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的正确方法 Pexpect脚本返回输出为“None”。

英文:

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 = &#39;ls&#39;
child = pexpect.spawn(dcommand)
child.expect(r&#39;.*$&#39;) # my prompt ends with $, if yours ends with something else, then use that
print(child.readline()) 

(pilenv) bash-5.0$ python ll.py 
b&#39;agust.py\t     IMG-20191213-WA0000.jpg  lib    l.py\r\n&#39;
(pilenv) bash-5.0$ 

Also please refer the code for a sane way to use pexpect which i did for something personal Pexpect脚本返回输出为“None”。

答案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 = (&#39;ls&#39;)
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

huangapple
  • 本文由 发表于 2020年1月3日 19:30:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定