This is an automated email from the ASF dual-hosted git repository.

brondsem pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/allura.git


The following commit(s) were added to refs/heads/master by this push:
     new 5c508e379 better --profile behavior for scripts, add option for 
outputfile
5c508e379 is described below

commit 5c508e3795b4d44f35149505347f3e1aaa86c2b5
Author: Dave Brondsema <dbronds...@slashdotmedia.com>
AuthorDate: Mon Jan 8 17:34:59 2024 -0500

    better --profile behavior for scripts, add option for outputfile
    
    and check outputfile writability at beginning, rather than at end
    See https://stackoverflow.com/a/48622889 about cProfile change
---
 Allura/allura/command/script.py | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)

diff --git a/Allura/allura/command/script.py b/Allura/allura/command/script.py
index 92384d1b5..52e58b2fb 100644
--- a/Allura/allura/command/script.py
+++ b/Allura/allura/command/script.py
@@ -38,6 +38,8 @@ class ScriptCommand(base.Command):
     parser = base.Command.standard_parser(verbose=True)
     parser.add_option('--profile', action='store_true', dest='profile',
                       help='Dump profiling data to <script>.profile')
+    parser.add_option('--profile-output', dest='profile_output',
+                      help='full path to store profiling results')
     parser.add_option('--pdb', action='store_true', dest='pdb',
                       help='Drop to a debugger on error')
 
@@ -60,11 +62,22 @@ class ScriptCommand(base.Command):
             with open(filename) as fp:
                 ns = dict(__name__='__main__')
                 sys.argv = self.args[1:]
+                code = compile(fp.read(), filename, 'exec')
+
+                if self.options.profile:
+                    profile_output_file = self.options.profile_output or 
'%s.profile' % os.path.basename(filename)
+                    if not os.access(os.path.dirname(profile_output_file), 
os.W_OK):
+                        raise OSError(f'no write permission to dir for 
{profile_output_file}. '
+                                      f'Specify a different path with 
--profile-output')
+                    # https://stackoverflow.com/a/48622889
+                    pr = cProfile.Profile()
+                    pr.enable()
+
+                exec(code, ns)
+
                 if self.options.profile:
-                    cProfile.run(fp.read(), '%s.profile' %
-                                 os.path.basename(filename))
-                else:
-                    exec(compile(fp.read(), filename, 'exec'), ns)
+                    pr.disable()
+                    pr.dump_stats(profile_output_file)
 
 
 class SetToolAccessCommand(base.Command):

Reply via email to