Documents some Python tips and tricks
Contents
Use the optparse standard module.
To disable interspersed arguments (i.e to stop option processing at the first non-option), call disable_interspersed_args on your parser.
for (index, value) in enumerate (sequence):
# ...
Christophe Simonis suggests using the itertools library , but I prefer the non-optimized version (simpler):
for (index,value) in reversed(list (enumerate (sequence))):
doStuff ()
Use the built-in function int (string, [base]).
If you know that your string is going to be in a base lower than 11, you can use the str.isdigit function to check that your string indeed contains a number.
Use the built-in function format:
format (number, 'd') # For base 10 format (number, 'x') # For base 16 format (number, 'o') # For base 8 format (number, 'b') # For base 2
See the specifications for more on format
In general, the subprocess standard module is to be used to manage external processes. However, I have coded two helper functions for common tasks.
Use svlib.servicerunner.Runner.callCmd (['your_cmd', 'your_arg1', ...]) . It throws an UnexpectedStatusError if the return status is not zero (or the one expected, see code for more)
Use svlib.servicerunner.Runner.callCmdGetOutput(['your_cmd', 'your_arg1',...]).
The usage is similar to callCmd, but it returns a tuple (returncode, stdoutString, stderrString). See code for more.
Use os.chdir(path)
Often, I want to transform a shell command given as a string, such as cat /etc/foo.txt "file with space" into a list of arguments to pass to e.g callCmd.
Of course str.split is not enough here, since it will just ignore quoted arguments. The solution is to use shlex.split.