6

Is it possible to write python one-liner, which will be listen on specific tcp port, accept connections, and response nothing.

I can do this in two lines:

import socket; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.bind(("", 5555)); s.listen(1); accepter = s.accept();
while True: data = accepter[0].recv(1024);

But I want to run this from python -c, So it should be one line.

How can I achieve this?

Nikolai Golub
  • 3,327
  • 4
  • 31
  • 61
  • 1
    Note: http://stackoverflow.com/questions/2043453/executing-python-multi-line-statements-in-the-one-line-command-line – Veedrac Sep 02 '14 at 00:44

1 Answers1

7

Using itertools.count and reduce (In Python 3.x, you need to use functools.reduce):

import socket, itertools; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.bind(('', 5555)); s.listen(1); accepter = s.accept(); reduce(lambda x, y: accepter[0].recv(1024), itertools.count())

You can also use other infinite iterator like itertools.cycle or itertools.repeat.

Following lines are an expanded version of above one-liner.

import socket, itertools
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 5555))
s.listen(1)
accepter = s.accept()
reduce(lambda x, y: accepter[0].recv(1024), itertools.count())
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • @kingsdeb, With `-c` option python interpret the given string as a program content. – falsetru Sep 01 '14 at 16:21
  • Traceback (most recent call last): File "", line 1, in File "socket.py", line 2, in s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.bind(("", 5555)); s.listen(1); accepter = s.accept() AttributeError: 'module' object has no attribute 'AF_INET' – bluefoggy Sep 01 '14 at 16:21
  • @kingsdeb, What is you python version? What is your platform? – falsetru Sep 01 '14 at 16:23
  • Python 2.7.5 on Fedora 20 – bluefoggy Sep 01 '14 at 16:25
  • @kingsdeb, It should work. I tested this in Python 2.7.6/3.4.0 in Ubuntu 14.10 and in Python 2.7.8/3.4.1 in Windows 7. http://asciinema.org/a/11870 – falsetru Sep 01 '14 at 16:29
  • yeah it works, I got that error because i had a file socket.py in the working dir. Removing the .py and .pyc files make it work.. It was so stupid. – bluefoggy Sep 01 '14 at 16:34
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/60405/discussion-between-kingsdeb-and-falsetru). – bluefoggy Sep 01 '14 at 16:38