1

Here is my problem: on reading a book on networking programming for python, i stumbles across this code:

import socket, sys
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

if sys.argv[1:] == ['server']:
    s.bind('127.0.0.1', PORT)
    ...
    ... 

and so on. My question is whether the if statement checks if any of the elements in the sys.argv list(except the first item) is compared to be equal to 'server'. I tried doing this in IDLE for Python 3.2 and it didn't work. The book is intended for python 2.7 so I tried that too but it still dint work.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895

4 Answers4

3

No, it checks whether the list formed by the slice 1: is equal to the list ['server'].

Community
  • 1
  • 1
mikołak
  • 9,605
  • 1
  • 48
  • 70
3

sys.argv[0] is the name of the program, which is stripped. sys.argv[1:] - all the command line arguments provided to the program.

The if statement checks that your script received only one argument server.

mishik
  • 9,973
  • 9
  • 45
  • 67
3

No, that wouldn't work in any version of Python. The only thing that does is to check that sys.argv from position 1 onwards has only one element, which is 'server'.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

You can check 'server' argument whith this construction:

if 'server' in sys.argv[1:]:
    do_something()

For future, use argparse for get command line arguments.

Michael Kazarian
  • 4,376
  • 1
  • 21
  • 25