Search code examples
pythonshellncursescursespython-curses

Python curses does not work with command substitution


I was using python project pick to select an option from a list. Below code returns the option and index.

option, index = pick(options, title)

Pick uses curses library from python. I want to pass the output of my python script to shell script.

variable output = $(pythonfile.py)

but it gets stuck on the curses screen. It cannot draw anything. What can be the reason for this?


Solution

  • pick gets stuck because when you use $(pythonfile.py), the shell redirects the output of pythonfile.py as if it were a pipe. Also, the output of pick contains characters for updating the screen (not what you want). You can work around those problems by

    • redirecting the output of pythonfile.py to /dev/tty
    • ensuring that your pythonfile.py writes its result to the standard error, and
    • directing the standard error in the shell script to the output of the $(...) construct.

    For example:

    #!/bin/bash
    foo=$(python basic.py 2>&1 >/dev/tty )
    echo "result '$foo'"
    

    and in pythonfile.py, doing

    import sys
    
    print(option, index, file=sys.stderr)
    

    rather than

    print(option, index)