python os.popen.readlines异常,python popen.stdout.readline()挂起

Im having a problem... does anyone knows why this code hangs in the while loop. The loop doesn't seem to catch the last line of the stdout.

working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)

line = working_file.stdout.readline()

working_file.stdout.flush()

while working_file != "" :

print(line)

line = working_file.stdout.readline()

working_file.stdout.flush()

the script hangs with the curser just blinking when readline() is encountered. I dont understand why. can anyone shed some light

Thanks all

jon

解决方案

Does doing a nonblocking read help you out?

import fcntl

import os

def nonBlockReadline(output):

fd = output.fileno()

fl = fcntl.fcntl(fd, fcntl.F_GETFL)

fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

try:

return output.readline()

except:

return ''

working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)

line = nonBlockReadline(working_file.stdout)

working_file.stdout.flush()

while working_file != "" :

print(line)

line = nonBlockReadline(working_file.stdout)

working_file.stdout.flush()

I'm not sure exactly what you're trying to do, but will this work better? It just reads all the data, instead of reading only one line at a time. It's a little more readable to me.

import fcntl

import os

def nonBlockRead(output):

fd = output.fileno()

fl = fcntl.fcntl(fd, fcntl.F_GETFL)

fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

try:

return output.read()

except:

return ''

working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)

stdout = ''

while working_file.poll() is None:

stdout += nonBlockRead(working_file.stdout)

# we can probably save some time and just print it instead...

#print(stdout)

stdout = stdout.splitlines()

for line in stdout:

print(line)

Edit: A generalized script which should be more suited for your use case:

import fcntl

import os

def nonBlockRead(output):

fd = output.fileno()

fl = fcntl.fcntl(fd, fcntl.F_GETFL)

fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

try:

return output.read()

except:

return ''

working_file = subprocess.Popen(["/pyRoot/iAmACrashyProgram"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)

while working_file.poll() is None:

stdout = nonBlockRead(working_file.stdout)

# make sure it returned data

if stdout:

# process data

working_file.stdin.write(something)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值