pythonline-profiler

Using line_profiler for an entire script without a main() function


I've just built a Raspberry Pi as a basic speed camera and want to make some tweaks to existing code. I've programmed before in various languages on and off for lots of projects, but not as a dedicated job.

The code that I'm using is this (it's quite long so I haven't posted it here):

https://github.com/gregtinkers/carspeed.py

I'd like to start by using line_profiler to help tweak the existing code where possible, slowly allowing me to make changes and learn how it works.

I've tried converting the existing script so that;

  1. The entire code is held within a 'main()' function, including the existing functions,
  2. Moving the code below the existing function definitions into a new 'def main():' function,

These result in me changing a lot of the existing code to get it to work, which it invariably doesn't and I end up getting lost!

I've followed various guides on using line_profiler and have it working with the existing defined functions, but I want to extend that to the rest of the code.

Am I missing a very easy method of doing this? How should I approach it?


Solution

  • I cannot test the code as I do not have a Rasberry Pi, but I would try this starting at line 57 (after your existing function defs). Basically you are defining a main() function, then calling it if the file is called as a script (What does if __name__ == "__main__": do?).

    def main():
        # define some constants
        DISTANCE = 76  #<---- enter your distance-to-road value here
        ...
        if (state == WAITING):
            ...
            # if the `q` key is pressed, break from the loop and terminate processing
            if key == ord("q"):
                return False #<=== note return instead of break 
             
        # clear the stream in preparation for the next frame
        rawCapture.truncate(0) 
    
    #End of main()
    
    if __name__ == '__main__:
        main()
        # cleanup the camera and close any open windows
        cv2.destroyAllWindows()