0

I have a python program which takes an input (a single character, 'y' or 'n') from the user and then executes a certain task based on that input. My need is to allow this program to run continuously from the terminal until I decide to stop it. Currently, I have to keep going back to the terminal and execute the program from there (and always type in that single character).

PS: If it helps: the program adds data to a MySQL database, so I need this in order to make the whole process automated (and thus a bit quicker)

EDIT

My my-program.py looks like this:

main():
    if input().lower()=='y':
        #does something here
    else:
        #does something else

My requirement was to run a Python program infinitely from the Terminal. I do know how to use loops and how to perform tasks based on user input. What I wanted was to automatically give 'n' as the input character input whenever prompted.

my-program.py performs a certain operation when a character is given as input. When i call my-program.main() from another Python program using a while loop as below, I want to keep passing the same input (say 'n') whenever prompted (when the input() statement of my-program.py is executed)

import my-program
while True:
    my-program.main()
Anubhav Dinkar
  • 343
  • 4
  • 16

2 Answers2

0

First install keyboard package:

pip3 install keyboard

Then write the code:

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
        else:
            pass
    except:
        break  # if user pressed a key other than the given key the loop will break

Soruce: Keyboard input detection

pedro_bb7
  • 1,601
  • 3
  • 12
  • 28
0

General case: the 'yes' command, it would use 'y' as your default option and won't ask you over and over again.

$man yes

yes - output a string repeatedly until killed [...]

DESCRIPTION: Repeatedly output a line with all specified STRING(s), or 'y'. It is probably equivalent to --force-yes and thus dangerous. If you still want to do it, you pipe the output of yes:

yes | <command>
bsikriwal
  • 178
  • 3
  • 15