2

This is quote from an DeathByCaptcha API documentation I am using.

dict deathbycaptcha.Client.decode(file imageFile, int timeout)
dict deathbycaptcha.Client.decode(str imageFileName, int timeout)

It can either accept path to image file or the file object

I have this line of code.

client.decode(urllib.urlopen('https://example/image.jpg').read(), 30)

But its giving me error because .read() does returns file-like object.

My preference is to do it in one line.

Is there any way I can easily cast that stream read by read() to file-like object?

If not possible in one line like we do in PHP (string) 100 then I will accept a multi-line

Umair Ayub
  • 19,358
  • 14
  • 72
  • 146
  • Do you want it to be a single line so that your code is succinct to read? If so, you could just create a function that reads from a URL and returns a file object. – Alex W Jan 18 '17 at 14:31
  • @AlexW Umm if not possible in one line like we do in PHP `(string) 100` then I will accept a multi-line solution. – Umair Ayub Jan 18 '17 at 14:32
  • [Python - open read and close a file in 1 line of code](http://stackoverflow.com/questions/8011797/open-read-and-close-a-file-in-1-line-of-code) – Alex W Jan 18 '17 at 14:37

1 Answers1

3

I am not sure about urllib.urlopen, but you can use urllib2.urlopen method to get file-like object you can pass to decode function. It will look more or less like:

client.decode(urllib2.urlopen('https://example/image.jpg'), 30)

EDIT: I took a look at urllib documentation and it looks like urllib.urlopen also returns file-like object.

running.t
  • 5,329
  • 3
  • 32
  • 50
  • @Unimar cool :), just keep in mind that error handling is missing in this one-liner so it will just throw exception in case of any issues (with connection e.g.). – running.t Jan 18 '17 at 14:42
  • Yeah i can understand ... I wanted "one-liner" solution and you provided it . thanks – Umair Ayub Jan 18 '17 at 14:44