Search code examples
pythonlinuxsubprocess

Prevent "smem" command to use terminal width, Need to use custom width


I want smem to capture whole output i.e. command name should fully capture agnostic of terminal width.

I see -a option is there but its tied up with current terminal width.

I want to use custom width, for that I tried below thing to set env={'COLUMNS':'512'} in subprocess.check_output() but this is not working for only smem command and works for top command.

smem should take width as 512 but its taking upto terminal width only.

Using Linux environment


Solution

  • If you are talking about https://selenic.com/repo/smem the source code does not seem to pay attention to the COLUMNS variable at all, which is however supported by many other tools.

    Instead, the tool calls stty size and expects to receive two integers back.

    As a crude workaround, you can hack your own wrapper. Perhaps something like this:

    #!/bin/sh
    if [ "$COLUMNS" ] && [ "$ROWS" ] && [ "$STTY_FORCE_COLUMNS_ROWS" ]; then
         echo "$COLUMNS $ROWS"
    else
         exec /usr/bin/stty "$@"
    fi
    

    If you save this in /usr/local/bin/stty (and chmod +x etc) it will redirect to the real stty in /usr/bin unless you have set the three variables COLUMNS, ROWS, and STTY_FORCE_COLUMNS_ROWS. You could then call smem like

    import subprocess
    from os import environ
    
    env = environ.copy()
    env['COLUMNS'] = '512'
    env['ROWS'] = '400'
    env['STTY_FORCE_COLUMNS_ROWS'] = 'yes, please'
    
    result = subprocess.check_output(['smem'], env=env)
    

    A better solution would be for smem to allow you to import its code (it too is written in Python); but the way the code is currently designed, you can't really.