Home  >  Q&A  >  body text

python - 使用subprocess调用外部程序,p.stdout读取内容卡死

import subprocess
import os
r=open("sad.txt",'a')
p = subprocess.Popen("ssh.exe root@192.168.58.154", stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = False)
p.stdin.write('password\n')
p.stdin.write('ifconfig\n')

while p.stdout.readline()!=' ':
    line = p.stdout.readline()    #如果p.stdout中内容被读完之后,程序会卡在这里
    #line = line.strip()
    print line
    r.write(line)   

这个卡死如何解决,这时候结束当前进程也没办法结束
或者如何判断卡死,然后p.kill()或“ctrl+c”当前进程
ssh执行p.stdin.write('exit\n')也不行,因为ssh exit之后还会跳回登录界面,进程还是没有结束

大家讲道理大家讲道理2741 days ago1277

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 09:05:10

    while p.stdout.readline()!=' ':
        line = p.stdout.readline()    #如果p.stdout中内容被读完之后,程序会卡在这里
        #line = line.strip()
        print line
        r.write(line)  
        

    First of all, I point out that there is a problem with this paragraph. This is a printing problem. p.stdout.readline() != '' should not be placed in a while, because after the data is read, it will be discarded, so The complete data cannot be printed or written to the sad.txt file. Secondly, I think p.stdout should be made non-blocking to solve the stuck problem

    import subprocess
    import os
    import fcntal
    
    r=open("sad.txt",'a')
    p = subprocess.Popen("ssh.exe root@192.168.58.154", stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = False)
    flags = fcntl.fcntl(p.stdout, fcntl.F_GETFL)
    flags |= os.O_NONBLOCK
    fcntl.fcntl(p.stdout, fcntl.F_SETFL, flags)
    p.stdin.write('password\n')
    p.stdin.write('ifconfig\n')
    
    while True:
        try:
            line = p.stdout.readline()    #如果p.stdout中内容被读完之后,程序会卡在这里
            if line == '':
                break
            #line = line.strip()
            print line
            r.write(line)
        except IOError:
            break

    reply
    0
  • PHPz

    PHPz2017-04-18 09:05:10

    This stuck is probably caused by the ssh process not exiting.

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 09:05:10

    The reason why it gets stuck is because the pipe is empty after reading the last line, and for the ifconfig command, the last line is not a space but n:

    p.stdin.write('ifconfig eth0\n')
    for line in iter(p.stdout.readline, '\n'):
        print line.strip()

    To prevent death caused by IO, the officially recommended method is to use communicate, such as this:

    out, err = p.communicate('ifconfig')

    reply
    0
  • Cancelreply