Zsh: select generated files with (om[1]) glob qualifiers

Rapid file generation.

I’ve recently been using memray, a memory profiler for Python, to optimize the startup memory usage (and time) for a client. It’s a fantastic tool, but its flexibility hampers getting instant feedback. It takes three commands to profile a program, generate a flame graph from the profile, and open the flame graph in the browser:

  1. $ memray run manage.py check
    Writing profile results into memray-manage.py.60450.bin
    
    System check identified no issues (17 silenced).
    [memray] Successfully generated profile results.
    
    You can now generate reports from the stored allocation records.
    Some example commands to generate reports:
    
    /.../python -m memray flamegraph memray-manage.py.60450.bin
    
  2. $ memray flamegraph memray-manage.py.60450.bin
    Wrote memray-flamegraph-manage.py.60450.html
    
  3. $ open -a Firefox memray-flamegraph-manage.py.60450.html
    

Notice that commands 1 and 2 generate files whose names need copying to the next one. While the names are predictable, they include the process ID, which changes each time you run the process, making scripting awkward.

In Zsh, we can avoid copying such generated filenames by using glob qualifiers, which are extra syntax you can add to filename globs in Zsh. Specifically, we want to attach the glob qualifiers om[1], which mean:

Attaching these qualifiers to appropriate globs allows commands to pick up a generated file without knowing its exact name.

For example, step 2 can be written:

$ memray flamegraph memray-*.bin(om[1])

Thus, the whole process can be turned into a one-liner:

$ memray run manage.py check && memray flamegraph memray-*.bin(om[1]) && open -a Firefox memray-flamegraph-*.html(om[1])

Boom!

Fin

May your globs qualify as great,

—Adam


😸😸😸 Check out my new book on using GitHub effectively, Boost Your GitHub DX! 😸😸😸


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Tags: