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.
4 Answers 4
No, it checks whether the list formed by the slice 1:
is equal to the list ['server']
.
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
.
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'
.
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.