python - 使用subprocess调用外部程序,p.stdout读取内容卡死
大家讲道理
大家讲道理 2017-04-18 09:03:10
0
3
1272
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之后还会跳回登录界面,进程还是没有结束

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

répondre à tous(3)
左手右手慢动作
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
PHPzhong

这个卡死应该是由于ssh这个进程没退出造成的。

小葫芦

之所以卡死是因为读完最后一行后管道空了,而且针对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')
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!