2

I want to get the contents of a file with ftplib and store it in a string variable in python. My first attempt is below. I guess lambdas can't contain assignment -- maybe because a lambda is a function + variables that should be self contained (?).

contents = ""
ftp.retrlines("RETR " + filename, lambda s: contents=s) #lambda cannot contain assignment

Anyway, do I need to capture output to stdout or is there an easier way?

bernie2436
  • 22,841
  • 49
  • 151
  • 244
  • http://stackoverflow.com/questions/9969247/creating-list-from-retrlines-in-python I think answers your question with regards to implementation I think the lambda does not work because it is not a callback but not smart enough to be sure – PyNEwbie Feb 14 '14 at 15:56

2 Answers2

1
outStr = StringIO.StringIO() # Use a string like a file.
ftp.retrlines('RETR ' + fileToGet, outStr.write)
print outStr.getvalue()
outStr.close()

https://docs.python.org/2/library/stringio.html

Aaron
  • 295
  • 4
  • 13
0

Firstly, this fails because python does not allow statements inside lambdas, only pure expressions.

Secondly, even if you did this as a function, i,e.:

contents = ""
def assign(s):
    contents=s
ftp.retrlines("RETR " + filename, assign )

it would fail, because by running contents=s you are just creating a local variable, not referencing the (global) variable contents.

You could further correct it as such:

contents = ""
def assign(s):
    global contents
    contents=s
ftp.retrlines("RETR " + filename, assign )

But this (using globals) is generally considered a bad practice. Instead, you should probably rethink your callback to actually do everything you need to do with the data. This is not always easy; you may want to keep functools.partial in a handy place in your programming belt.

loopbackbee
  • 21,962
  • 10
  • 62
  • 97