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

做无阻塞读取会帮助你吗?

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

我不确定你要做什么,但这会更好吗?它只读取所有数据,而不是一次只读取一行.它对我来说更具可读性.

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)

编辑:一个更适合您的用例的通用脚本:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值