2.9.1. Explanation of less familiar Python statements from Topic 1 – Sockets

#!/usr/bin/env python

Found through out the book. When using Windows, this is just a comment and is ignored. The shell of Unix / Linux computers uses this line to determine how to process the file. With this line, the file may be executed directly with out passing the file name as command line argument to the python program.

host = sys.argv[1]

Found on page 10 and similar usage through the book. This reads the command line arguments passed to the program. If the program is invoked either from a DOS command prompt or from a Unix shell, then sys.argv is a list of strings representing what was typed at the command line. For example, if one starts a program as follows:

C:> python myprogram.py foo bar zoo

Then sys.argv would be the list: ['myprogram.py', 'foo', 'bar', 'zoo']. So in this case, sys.argv[1] would be ‘foo’. Command line arguments are a very simple mechanism for passing data to a program. If command line arguments are needed, then the program must be started by typing commands at some sort of shell prompt, which for those used to starting programs by clicking on icons, seems inconvenient. However, the convenience of getting data into the program may make it worth while to use the command line. The command line also make it easier to view error messages and debug programs. If you click on an icon to start a program from Windows, then if there is an error, which causes the program to exit, the console window showing the output will disappear before you get the chance to read the error message. The command prompt eliminates this problem.

port = int(textport)

Found on page 29. Here textport is a string, but an integer is needed so the int() function is used get an integer from the string.

sollist = [x for x in dir(socket) if x.startswith('SO_')]

Found on page 38. This is a List Comprehension to generate a list of options that may be set on socket objects. It uses the dir() function to get a list of attributes for the socket module and it filters that list using the string.startswith() function.

sollist.sort()

Found on page 38. Uses the list.sort() function to sort the list of strings. Being a list of strings, with no optional cmp() function supplied, it sort them alphabetically.

endpos = min(byteswritten + 1024, len(data))

Found on page 62. Uses the min() function to determine which is smaller between the end of the next full buffer of data that can be sent and the end of the data.

Previous topic

2.9. What Does That Line of Python Code Do?

Next topic

2.9.2. Explanation of less familiar Python statements from Topic 2 – DNS

This Page