[Tutor] Code critique
Stefan Behnel
stefan_ml at behnel.de
Fri Oct 24 15:03:49 CEST 2014
Bo Morris schrieb am 24.10.2014 um 14:03:
> May I please get a little instructional criticism. The code below works. It
> logs into 9 different Linux computers, runs a couple commands, and then
> transfers a file back to the server. I want to become a better Python
> coder; therefore, I was hoping for some ways to make the below code better,
> more efficient, or if I am doing something incorrectly, a correct way of
> doing it. Thanks
A quick comment, not related to coding style: take a look at fabric. It's
made for doing these things.
http://www.fabfile.org/
Regarding your program, instead of writing long sequences of repetitive if
conditions, I would write one function for each of the different operations
and store them in a dict, mapping each host name to a function (and
multiple host names may map to the same function). Then, look up the host
name in the dict and call the corresponding function to run the right
operations on that host.
Using functions will make it easier to factor out similar code. If you look
at the different operations that you do on the different hosts, you will
notice that most of them do the same thing, just with different files.
Instead of duplicating your code for each host, extract the file names that
each host needs and then pass it into the function that reads the file from
the host. The function will then be the same for all hosts, only the input
arguments change.
Stefan
More information about the Tutor
mailing list