At work I am modifying an existing tool to work from the command line instead of a GUI. Currently everything is a bit coupled to the GUI. On Friday, the next problem I encounted was a global variable in Common.py that was not initialized.
""" Common.py """ def initHSCM(): global hSCManager ... hSCManager = win32serviceOpenSCManager(None, None, win32con.SERVICE_ALL_ACCESS) ... ... def startService(service): """ function that uses hSCManager """ # These functions don't work when hSCManager is set to None def stopService(service): """ function that uses hSCManager """ # These functions don't work when hSCManager is set to None ...
The only place it is getting initialized is when iniHSCM() is called from GUI.py.
""" GUI.py """ Common.initHSCM() ... startService("blah") ... stopService("blah")
My new CLI.py does not uses Common.py as well as the other underlying libraries. Instead of just calling initHSCM() inside CLI.py so that calls to Common.py, I decided to rewrite all the functions that use the hSCManager global variable (ie. startService, stopService, and many others). My plan was to rewrite them to not depend on this global variable, and make them a bit cleaner. Instead they would get an hSCManager handle and close it at the end. So service manager objects would be shorter-lived things. Like most of the code in this project, it's a rat's nest and was written by people who knew C and Java better than they knew python. So part of my motivation for re-writing was to clean things up a bit. After I had re-writen a few of the functions, I realized that I had unknowingly creating new bugs (in the functions I was writing). Even though I was writing some unit tests (which was making the development process take longer on the whole) I knew that the code I was writing was going to have more bugs in it than the code that had essentially been working and stable for years (albeit ugly). The last thing I need is bugs in this code. When bugs happen I want to know that they are most likely in my new code.
In the end, I gave up and this is what I did:
""" CLI.py """ Common.initHSCM() # easy hack ... startService("blah") ... stopService("blah")
An even easier way is to move responsibility for initializing hSCManager into Common.py. Something like this?
""" Common.py """ hSCManager = win32serviceOpenSCManager(None, None, win32con.SERVICE_ALL_ACCESS) ... def startService(service): """ function that uses hSCManager """ # These functions don't work when hSCManager is set to None def stopService(service): """ function that uses hSCManager """ # These functions don't work when hSCManager is set to None ...
Hmm, that was easy. Moral of the story: don't re-write code that is several years old and works unless you really, really have to. Who cares if it's ugly and a hack. You didn't write it.
Add new comment