Question

MS = 'M-SEARCH * HTTP/1.1\r\nHOST: %s:%d\r\nMAN: "ssdp:discover"\r\nMX: 2\r\nST: ssdp:all\r\n\r\n' % (SSDP_ADDR, SSDP_PORT)

On checking this line with PEP8, it says "line too long"

So I break it like this:

MS = 'M-SEARCH * 
      HTTP/1.1\r\n
      HOST: %s:%d\r\n
      MAN: "ssdp:discover"\r\n
      MX: 2\r\n
      ST: ssdp:all\r\n\r\n
      ' % (SSDP_ADDR, SSDP_PORT)

But I am still getting so many errors.

Please review this.

Was it helpful?

Solution 2

Use python's implicit string concatenation and implicit line concatenation inside unterminated brackets/parenthesis...:

MS = ('M-SEARCH * '
      'HTTP/1.1\r\n'
      'HOST: %s:%d\r\n'
      'MAN: "ssdp:discover"\r\n'
      'MX: 2\r\n'
      'ST: ssdp:all\r\n\r\n') % (SSDP_ADDR, SSDP_PORT)

Note that some (including Guido) seem to dislike implicit string concatenation. If you fall into that category, you can use explicit concatenation (just add a +'s where necessary). There's no real harm in doing this -- the bytecode optimizer will optimize the concatenation away just the same as it does with implicit concatenation.

OTHER TIPS

Use Python's multiline strings:

MS = """M-SEARCH * 
      HTTP/1.1\r\n
      HOST: %s:%d\r\n
      MAN: "ssdp:discover"\r\n
      MX: 2\r\n
      ST: ssdp:all\r\n\r\n
      """ % (SSDP_ADDR, SSDP_PORT)

But be aware that this will change indentation and add extra newlines (which might or might not be a concern for your use case).

This is the solution I think would work for now. Splitting the lines into strings.

MS = 'M-SEARCH *' + \
  'HTTP/1.1\r\n' + \
  'HOST: %s:%d\r\n' + \
  'MAN: "ssdp:discover"\r\n' + \
  'MX: 2\r\n' + \
  'ST: ssdp:all\r\n\r\n' % (SSDP_ADDR, SSDP_PORT)

You can't break strings like that. Use a backslash:

MS = 'M-SEARCH * \
HTTP/1.1\r\n \
HOST: %s:%d\r\n \
MAN: "ssdp:discover"\r\n \
MX: 2\r\n \
ST: ssdp:all\r\n\r\n \
' % (SSDP_ADDR, SSDP_PORT)

Or use triple-quotes. This will add newlines so you can drop the last \n in your strings:

MS = """M-SEARCH * 
HTTP/1.1\r
HOST: %s:%d\r
MAN: "ssdp:discover"\r
MX: 2\r
ST: ssdp:all\r\n\r
""" % (SSDP_ADDR, SSDP_PORT)

Notice that the indentation matters in both cases.

If you're generating HTTP requests, there are plenty of libraries for that. Why not use one? Check out requests, urllib2 or urllib3

enclosing within brackets is an alternative solution I use it extensively to tackle this long line issue

including @mgilson suggestion to include + to be explicit

MS = ("M-SEARCH *" +
  "HTTP/1.1\r\n" +
  "HOST: %s:%d\r\n" +
  "MAN: \"ssdp:discover\"\r\n" +
  "MX: 2\r\n" +
  "ST: ssdp:all\r\n\r\n") % (SSDP_ADDR, SSDP_PORT)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top