首页 > AttributeError: 'module' object has no attribute 'sendline'

AttributeError: 'module' object has no attribute 'sendline'

#!/usr/bin/python2.6 
# -*- coding: utf-8 -*-
# filename: pexpect_test.py

import pexpect,time,sys
def sendCommt():
    demo = open("result.txt", "ab")
    demo.write('==========Log Tile: demo==========\n')
    print "start link"
    child = pexpect.spawn('ssh %s@%s' % (user,ip))
    print "link to 10.10.16.24."
    child.expect("natsu@10.10.16.24's password: ")
    child.sendline(passwd)
    for cmd in cmds:
        time.sleep(2)
        p = pexpect.spawn(cmd)
        p.logfile = demo
        p.write('=====================\n')
        p.expect(pexpect.EOF)
        print cmd
    time.sleep(2)
    demo.close()
    child.close()
    print "done"

if __name__ == '__main__':
    user = 'natsu'
    ip = '10.10.16.24'
    passwd = '1'
    cmds = ['ps','ls','ls -l','ifconfig','date']
    # patterns = ['Are you sure you want to continue connecting (yes/no)?','password:']
    # CONTINUES,PASSWD = range(len(patterns))
    # flag = 'yes'
    try:
        sendCommt()
    except pexpect.TIMEOUT:  
        print "TIMEOUT" 
    # except pexpect.EOF:
    #     print "EOF"

在linux环境下运行Python
上面的代码可以运行通过
但是把p = pexpect.spawn(cmd) 改成 p = pexpect.sendline(cmd)后,就会报这个错误

这里有个类似的描述http://stackoverflow.com/questions/11403932/python-attributeerror-module-object-has-no-attribute-serial
但是照他的改法会报这个


看下面dir的结果,pexpect模块里面没有sendline这个方法,所以会报AttributeError.

>>> import pexpect
>>> dir(pexpect)
['EOF', 'ExceptionPexpect', 'Expecter', 'PY3', 'TIMEOUT', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__revision__', '__version__', 'exceptions', 'expect', 'is_executable_file', 'pty_spawn', 'run', 'runu', 'searcher_re', 'searcher_string', 'spawn', 'spawnbase', 'spawnu', 'split_command_line', 'sys', 'utils', 'which']

正确的用法示例如下:

# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
import pexpect
child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('Name .*: ')
child.sendline('anonymous')
child.expect('Password:')
child.sendline('noah@example.com')
child.expect('ftp> ')
child.sendline('lcd /tmp')
child.expect('ftp> ')
child.sendline('cd pub/OpenBSD')
child.expect('ftp> ')
child.sendline('get README')
child.expect('ftp> ')
child.sendline('bye')

要在pexpect.spawn(cmd)的返回值上调用sendline方法,参考:http://pexpect.readthedocs.org/en/stable/overview.html

【热门文章】
【热门文章】