0

This is a modification of my previous post. Based on this answer, I use the following for non-blocking read and write method (using Python 2.7):

from __future__ import print_function
from twisted.internet.task import react
from twisted.internet.defer import Deferred
from twisted.internet.fdesc import readFromFD, setNonBlocking

def getFile(filename):
    with open(filename) as f:
        d = Deferred()
        fd = f.fileno()
        setNonBlocking(fd)
        readFromFD(fd, d.callback)
        return d

def main(reactor, filename):
    d = getFile(filename)
    return d.addCallback(print)

react(main, ['/Users/USER1/Desktop/testfile.txt'])

In fact, I want to store the reading results into a list instead of using print in return d.addCallback(print). I tried the following:

def main(reactor, filename):
    d = getFile(filename)
    X = []
    return d.addCallback(X)

But it seems it is not correct. How can I store the reading results into a list?

Kristy
  • 251
  • 5
  • 12
  • In python2 `print` is a statement, you can't use it as an object. To do so try `from __future__ import print_function`. But why do you need `print` here? – Gennady Kandaurov Mar 13 '18 at 19:41
  • @GennadyKandaurov. Actually, I don't want to print. Print just confirms me that reading is successful. I want to store the reading results into an a list. I am trying to achieve that but still I am getting errors. I will edit my post – Kristy Mar 13 '18 at 20:03

1 Answers1

0

Since X is [] you're adding an empty list as a callback. An empty list isn't callable, though, so it's not usable as a callback.

Instead, you want something like X.append. X.append is callable (and with one argument). So it makes an alright callback.

return d.addCallback(X.append)

However, X.append returns None so the result of d becomes None after X.append has run. X is then inaccessible to any code in your example, so this might not be the most useful thing to do.

Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122
  • Thank you very much. Do you have a suggestion to achieve reading into a list, still by using twisted or any other non-blocking approach? – Kristy Mar 13 '18 at 20:15
  • This will read into the list. The question is what you want to happen next. Since this code is in your main function, the only thing that's going to happen next is the program will exit. So it sort of doesn't matter what's in `X`. If the change from `X` to `X.append` makes sense to you now, you might want to ask a new question that addresses the bigger picture of how to fit this into whatever your bigger picture is. – Jean-Paul Calderone Mar 13 '18 at 23:43