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
601k68 gold badges910 silver badges923 bronze badges
asked Aug 29, 2013 at 13:34
0

4 Answers 4

3

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

answered Aug 29, 2013 at 13:36
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.

answered Aug 29, 2013 at 13:37
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'.

answered Aug 29, 2013 at 13:37
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.

answered Aug 29, 2013 at 14:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.