0

If it was possible to get output from this shell script into a variable I think that would be the ideal solution.

import os
os.system('read -s -n 1 -p "Press any key to continue..."') 

I have a shell script that reacts to one keypress immediately (because "read" with the option "-n1" is selected) like this:

#!/bin/bash
read -s -n1 -p "" keypress
if test "$keypress" = "a"
then
    open ~/something.txt
fi
if test "$keypress" = "b"
then
    open ~/something_else.txt
fi
exit

How could I modify this to python 2 code to similarly react immediately to user input rather than waiting for the user to press return? (I use osx and would prefer a solution that only relies on the standard library, but anything that could work on both osx and linux would be fine.)

something=raw_input()
print "write a or b"
user_input_a='a'
user_input_b='b'
if something == user_input_a:
 print 'it was a'
if something == user_input_b:
 print 'it was b'
Var87
  • 519
  • 1
  • 4
  • 17
  • Are you on Windows? Try `msvcrt.getch`. – Kevin Jan 21 '15 at 13:58
  • Nope. I updated my question. :) – Var87 Jan 21 '15 at 14:00
  • trying sys.stdin.read(1), it seems like I still have to press return, I'd like something that works the same was as the bash code above – Var87 Jan 21 '15 at 14:03
  • 1
    Also see http://stackoverflow.com/questions/8718561/python-3-how-to-input-data-without-pressing-return-in-osx/8718648#8718648 – PM 2Ring Jan 21 '15 at 14:22
  • It is possible to get output from a shell script into a variable, but that's really not a good way to fetch a single character. Please see the answer linked in my previous comment for an OSX solution. – PM 2Ring Jan 21 '15 at 14:43
  • I saw it. That code as well as the code in the other answers mostly did not work when I attempted to copy paste it (with some modifications) and the code is a bit too complicated for me to fix it. I guess I'll stick with bash for now, but I've noted that the ncurses library may be a good option in the future. – Var87 Jan 21 '15 at 15:41

0 Answers0