0

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?

2
  • Where key_press comes from?..Is it the same in the while loop and the in key_inp function? Commented Jan 1, 2016 at 18:49
  • The bit of code example you are providing, has a local variable which is unused and later on an unassigned local variable. Could you edit with the actual example script you are trying to use? Commented Jan 1, 2016 at 19:04

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.