Reputation: 43
I have created a Python script that can take commands from a pipe (named pipe1). You can find the Script on Pastebin.
I tested the script with this other script:
import sys
fw = open("pipe1", "w" )
fw.write('fd\n')
fw.close()
and it worked.
Now I want to control the script with another Python script, that could write in the pipe if I press w
, a
, s
, d
or p
and display me the keys, that i press.
In this example I just want to print the keys that I press. I would later add the fw.write
commands to write in the pipe, which I tested before:
def key_inp(event):
print 'Key:', event.char
key_press = event.char
sleep_time = 0.030
while True:
try:
if key_press.lower() == 'w':
print "w"
elif key_press.lower() == 's':
print "s"
elif key_press.lower() == 'a':
print "a"
elif key_press.lower() == 'd':
print "d"
elif key_press.lower() == 'q':
print "q"
elif key_press.lower() == 'e':
print "e"
elif key_press.lower() == 'p':
print "stop"
except(KeyboardInterrupt):
print('Finished')
My problem is, that the script that i wrote (and improved with a stackoverflow member) closes immediately when i open it.
Can anyone explain me why, and how i can fix it so that the script stays open the whole time until i interrupt it with Ctrl+c?
Upvotes: 0
Views: 965
Reputation: 3462
EDIT: This answer relies on installing the readchar module. You can install it via pip: pip install readchar
.
The code you are trying to use has no functionality: you only define a function, but never call upon it. On top of that, it contains indentation errors.
Something along the lines of what you are trying to achieve, but with a dot as finish key:
import readchar
while True:
key = readchar.readkey()
key = key.lower()
if key in ('wsadqe'):
print 'Key:', key
elif key == 'p':
print "stop"
sleep_time = 0.030
if key == '.':
print "finished"
break
Upvotes: 2