【问题标题】:Pexpect script gives "None" for outputPexpect 脚本为输出提供“无”
【发布时间】:2020-01-03 11:30:06
【问题描述】:

以下脚本在服务器上运行时打印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 

有什么想法吗?我敢肯定这很傻,但是什么...

【问题讨论】:

  • Python 2 已结束生命周期,您应该升级到 Python 3

标签: python pexpect


【解决方案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 的理智方法,我是为个人做的:)

【讨论】:

    【解决方案2】:
    #!/usr/bin/env python
    import pexpect
    import sys
    dcommand = ('ls')
    child = pexpect.spawn(dcommand)
    child.expect(pexpect.EOF)
    output = child.before
    print(output)
    

    你需要添加 child.expect(pexpect.EOF) 你可以在https://pexpect.readthedocs.io/en/stable/api/pexpect.html找到更多信息

    【讨论】:

      猜你喜欢
      • 2022-12-22
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      相关资源
      最近更新 更多