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.

0

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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'.

Comments

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.

Comments

Your Answer

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.