Heim > Fragen und Antworten > Hauptteil
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之后还会跳回登录界面,进程还是没有结束
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
高洛峰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')