[Tutor] python sockets

Peter Otten __peter__ at web.de
Tue Jun 10 10:07:02 CEST 2014


Lukas Nemec wrote:

> Hi,
> 
> fist - are you really triyng to have open 64 000 ports? ok, i suppose
> you have your reasons, but this is not a good idea - you'll block most
> applications that use these ports ..
> 
> The problem is with your main function -
> you have PORT defined, but it is not global, it is only local, and when
> you add +1 to it, next spawned process will have PORT with previous value.
> 
> either use global PORT, or have it as a parameter for the function:
> 
> main(port):
>      ......
>      PORT = port
> 
> while startingPort<65535:
>     thread.start_new_thread(setup(startingPort))
>     startingPort=startingPort+1

setup() is still called in the main thread, likely listens forever which is 
why thread.start_new_thread() is never called and therefore doesn't complain 
about the missing argument...

Try

def setup(PORT):
   ... # don't reassign port inside the function

for port in range(startingPort, 65535):
    thread.start_new_thread(setup, (port,))

Note that

some_func(setup(port))

passes the result of the setup() call to some_func while

some_func(setup, (port,))

passes the setup function and a 1-tuple with the port as its only item. The 
comma is necessary to create a tuple, parentheses alone have no effect:

>>> (1)
1
>>> (1,)
(1,)


PS: You should also consider using the (higlevel) threading module instead 
of the thread module.




More information about the Tutor mailing list