0

If I am taking over stdout, with an interactive Python script that launches a console GUI such as curses or urwid; after some actions and closing the loop, how could I cd to a path printed in stdout?

For example,

import sys
import urwid

def check_for_q(key):
    if key in ('q', 'Q'):
        raise urwid.ExitMainLoop()

txt = urwid.Text(u"Thanks for helping")
fill = urwid.Filler(txt, 'top')
loop = urwid.MainLoop(fill, unhandled_input=check_for_q)
loop.run()

sys.stdout.write('/usr/bin')

When run, and pressing q or Q to quit the urwid loop:

(py27) $ python curses_script.py

/usr/bin

(py27) $

If this was a simple python script that only printed to stdout, I could cd $(python simple_script.py). With the above, however, this will hang as the python subshell fails to hijack stdout and process input.

Is it possible to work around this without writing to file?

  • The approach I have taken before is to create a little bash script wrapping the python script. The bash script creates a temporary file or a named pipe, feeds the path of this file to the python script as a command line argument, and then reads and subsequently deletes the file when the python script is finished. – jme Oct 29 '16 at 18:57
  • @jme I would rather avoid relying on creation of temp files and deleting them later. I have never used named pipes before, and will look into them. An example to illustrate would be fantastic! – AskingForAFriend Oct 29 '16 at 20:12
  • Why would you like to avoid the creation of temporary files? Using files in this way is pretty consistent with the Unix philosophy. Furthermore, named pipes are essentially files (there are several examples of using them on this site). – jme Oct 29 '16 at 20:43
  • @jme I started playing around with temp files using `mktemp` and had trouble writing to the file (even with `-u` flag). Not sure why yet. Unfortunately I can not try again until this evening, but hopefully will report back with some good news/snippet then. – AskingForAFriend Oct 30 '16 at 08:12
  • Just write to STDERR or to another file descriptor. – Joel Cornett Oct 30 '16 at 18:16

1 Answers1

0

Instead of doing some bash black magic, this could be accomplished pretty easily, and this is a working solution

temp_file=$(mktemp /tmp/curses_script.XXXXXX)
python curses_script.py temp_file
# write to temp file in script...
cd $(cat temp_file)
rm $temp_file