1

the following code checks for an open port and the socket seems to be running really slow:

for line in f.readlines():

            line = line.rstrip()

            with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
                if sock.connect_ex((ip, port)) == 0:
                    print(line + " ▲")
                    text = line + "\n"
                else:
                    print(line + " ▼")

Does anyone have any idea as to why it could be slow?

  • Readlines is the plague. Don't use readlines, ever. http://stupidpythonideas.blogspot.com.co/2013/06/readlines-considered-silly.html I mean... this is on SO already. http://stackoverflow.com/questions/17246260/python-readlines-usage-and-efficient-practice-for-reading#17246300 – Alfabravo May 18 '17 at 19:47
  • While that's bad, it's not what is slowing down the thing. He is creating a socket per each line in the file. – arboreal84 May 18 '17 at 19:48
  • @arboreal84 that's why i'm not answering but commenting. Right? Also, we don't know the size of the file so go figure... – Alfabravo May 18 '17 at 19:48
  • Remove this didn't affect it, although, cheers for the heads up – user7834940 May 18 '17 at 20:02

1 Answers1

1

You should only be creating a socket once, rather than once per each line of text. That might be what is slowing down your program.

Try to put the for loop inside the with block.

arboreal84
  • 1,856
  • 15
  • 19