首頁  >  問答  >  主體

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 天前1278

全部回覆(3)我來回復

  • 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)  
        

    首先,我指出這段是有問題的,這個是列印問題, p.stdout.readline() != '',不應該放在while中的,因為讀取資料後,就會捨棄掉了,這樣就不能把完整資料列印了,和寫入到sad.txt檔案了,
    其次我認為應該給p.stdout 搞成非阻塞,就可以解決卡死問題

    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

    回覆
    0
  • PHPz

    PHPz2017-04-18 09:05:10

    這個卡死應該是由於ssh這個進程沒退出造成的。

    回覆
    0
  • 高洛峰

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

    之所以卡死是因為讀完最後一行後管道空了,而且針對ifconfig指令來說,最後一行不是空格而是n:

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

    為防止出現因IO引起的死亡等,官方建議的做法是使用communicate,例如這樣:

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

    回覆
    0
  • 取消回覆