0

I have a CLI program in python that will run files. However, if a program is run that never stops, I want the user to be able to 'kill' that program, but not the whole script. The input for stopping the script could be the push of a certain key on the keyboard, I really have no clue how to do this and I couldn't find any answers here. I am using a os.system process, here is a snippet of my code and an example:

if os.path.isfile('../file'):
    cmd = os.path.join(os.getcwd(), '../file')
    os.system('{} {}'.format('python', cmd))
    print('Process finished')

And file contains the following code:

while True:
   print("Do stuff")

Please note that I cannot edit 'file' and I want to be able to stop the os.system process with a key pressed without killing the entire main script.

2 Answers2

1

You can encapsulate your block of code in a while loop that will run when the user enters text, and ends when a user enters an empty string (i.e. pressing the Enter or Return key).

while True:
    i = input("Enter text (or Enter to quit): ")
    if not i:
        break
      
    if os.path.isfile(selectedDir+'/'+file):
      cmd = os.path.join(os.getcwd(), selectedDir+'/'+file)
      os.system('{} {}'.format('python', cmd))
      print('Process finished')
  
    print("Your input:", i)
print("While loop has exited")

Alternatively, you can use try and except to handle an exception, and simply continue your program by using pass without error handling:

try:
  if os.path.isfile(selectedDir+'/'+file):
    cmd = os.path.join(os.getcwd(), selectedDir+'/'+file)
    os.system('{} {}'.format('python', cmd))
    print('Process finished')
except Exception:
  # Your script will continue
  pass
asultan904
  • 189
  • 7
  • 1
    This does not work. All this does is stops the program from running. – PythonDudeLmao Oct 16 '22 at 03:54
  • 1
    Also, try and except statements do not work on os.system. What I need is a way to stop my process while it is running by detecting a key pressed (without stopping the whole script) – PythonDudeLmao Oct 16 '22 at 03:55
0
from subprocess import Popen,PIPE

is_running = False
if os.path.isfile('../file'):
    cmd = os.path.join(os.getcwd(), '../file')
    #os.system('{} {}'.format('python', cmd))
    proc = Popen(["python3", "-m", cmd],stdout=PIPE, stderr=PIPE)
    is_running = False
    while is_running:
    try: 
       output, error = proc.communicate()
    except KeyboardError:
       is_running = False
       #Here if Ctrl+C pressed you can exit the program with next line -> Uncomment 
       #proc.kill()
       #IF you want the script to continue after exiting the program all you have to do is uncomment the PASS in next line
       #pass 

    print('Process finished')

You can modify this to check any Key pressed. I'll tag that info here;

To Check For Specific Keyboard Input
Another answer, an overkill, but will do your job

spramuditha
  • 357
  • 2
  • 9
  • This is almost what I am looking for! But, for some reason, when the files are run, it doesn't print. Thanks anyway! – PythonDudeLmao Oct 16 '22 at 06:50
  • You mean you are not getting the expected output from "file"? I am sorry I can't help as you have not given enough information about that file. From what I see as long as this is a normal python file ```while True: print("stuff")``` should work without any issue. – spramuditha Oct 16 '22 at 21:08
  • Okay, sorry it showed as if. Hope you manage to get the job done? – spramuditha Oct 21 '22 at 00:24