Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Profiling a python 3.6 module from the command line

I have a python project where I execute the app as a module using the -m flag. So something like:

python -m apps.validate -i input.mp4

Now, I want to profile it using the command line. So the inline examples suggest invoking cProfile itself a module. However, I cannot do something like:

python -m cProfile apps.validate -i input.mp4

However, this results in the error "No such file or directory". I cannot just go to the apps directory and launch validate.py due to relative imports.

Is there a way to profile a module on the command line?

like image 628
Luca Avatar asked Aug 01 '26 12:08

Luca


1 Answers

Instead of running cProfile in shell, maybe you can use cProfile in your python script by adding some code in apps.validate or creating a new script and import apps.validate like this. Maybe some typo below :)

import cProfile
import sys

def run_validate(args): 
    # run your apps.validate code with shell arguments args here
    pass

if __name__ == '__main__':
    pr = cProfile.Profile()
    pr.enable()
    run_validate(*sys.argv)
    pr.disable()
    pr.print_stats()

then just run the original script: python -m apps.validate -i input.mp4

like image 80
kuangchen Avatar answered Aug 03 '26 00:08

kuangchen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!