Prevent Python Interpreter from Exiting if CTRL-D is pressed - python

I am running a script with python -i main.py. The script starts some C threads and python threads using threading module, then python code ends and it goes to a prompt. How can i prevent python from exiting if CTRL-D is accidentally pressed? I don't want to press CTRL-D by accident (already happened twice) and suddenly the interactive interpreter is down with all its threads.
I need the to still have access to the interactive interpreter. The goal is to start the C threads and python threads, then monitor them later from python.
I tried using readline and binding ^D to nothing, but it would still terminate python.
Example (main.py):
print("Init code for python thread")
print("Init code for c thread")
When running this with python -i main.py, after the second line is finished, i get the prompt >>>. If i am at the prompt and press CTRL-D, it will start a systemExit. I want to prevent that at all costs.

If you are waiting on input then you can wrap the input call in try/except. Remember that Ctrl-D is effectively EOF.
Therefore this might be a useful pattern:
while True:
try:
v = input('Type something: ')
break
except EOFError:
print('You typed CTRL-D')
print(f'You typed {v}')

Related

Key press in a Python subprocess?

try:
subprocess.run(exe_path)
keyboard.press_and_release('enter')
print('Successful Extracted')
except Exception as exe:
print(exe.args)
keyboard.press_and_release('enter')
The point is to run the EXE of windows but it needs an input of keyboard to end its process, and it will remain stuck over there unless a keyboard input is given physically. Right now I am facing an issue as
subprocess.run('some_exe')
is running the process and after successfully run asking
Press Any Key To Exit
while I have already mentioned next to subprocess.run
keyboard.press_and_release('enter')
and it's coming to the next line unless we press the button from the keyboard manually
NOTE: python3.8
For the sake of a reproducible example, say we want to run the following Python script as a subprocess, let's call it script.py.
input('Press Enter to exit.')
It won't terminate until the user presses the Enter key. If we want to emulate the key press, we can just send a newline character to the subprocess's stdin using Popen.communicate. Like so:
from subprocess import Popen, PIPE
process = Popen(['python', 'script.py'], stdin=PIPE, text=True)
process.communicate('\n')
The external program doesn't have to be a Python script, it can be any executable. Just replace ['python', 'script.py'] with the corresponding command-line call, e.g. ['some_exe'].
Obviously this also works if the external program accepts any key to exit. Only sending special keys which don't have an obvious text representation, such as F1, would complicate things.
You can create a .vbs file to run your .exe file or python script without console debugging window:
Set oShell = CreateObject ("Wscript.Shell")
Dim strArgs
strArgs = "cmd /c python main.py"
oShell.Run strArgs, 0, false
If you have .exe file just replace python main.py with yourFile.exe.

Python freezes running exe file

I'm doing a simple python gui and on button click it will run a simple command:
os.system("C:/cygwin64/bin/bash.exe")
When I look in the console it ran correctly and but my guy freezes and is not responding.
If I run the the command in the console without python it works perfectly and I start cygwin terminal.
If you know what is cygwin is there a better way to start it in the same terminal?
os.system blocks the current thread, you can use os.popen in order to do that in another thread, and it also gives you few methods to detach/read/write etc' that process.
for example,
import os
a = os.popen("python -c 'while True: print(1)'")
will create a new process that will be terminated as soon as you terminate your script.
you can do
for i in a:
print(i)
for example, and it will block the thread as os.system does.
you can a.detach() it whenever you want to terminate the process.
However, os.system
import os
os.system("python -c 'while True: print(1)'")
it will output the 1s forever until you terminate the script.
You can use function Popen in package subprocess. It has many possible arguments that allow you to pipe input to and/or pipe output from the program you are running. But if you just want to execute bash.exe while allowing your original Python program to continue running and eventually wait for the completion of bash.exe, then:
import subprocess
# pass a list of command-line arguments:
p = subprocess.Popen(["C:/cygwin64/bin/bash.exe"])
... # continue executing
# wait for the subprocess (bash.exe) to end:
exit_code = p.wait()

Can't catch Ctrl+C in input() with Spyder 3.3

How do I capture Ctrl+C in line and exit the program as user enters it. I am using Python 3.7.3 on IPython 7.4.0 on spyder 3.3.3 on windows 64 bit machine with 8 GB RAM.
The most important thing is that when I run this program on windows powershell it works, this is happening only with spyder.
I tried using threads, KeyboardInterrupt, etc. but nothing works. I also saw lots of post regarding this but none is useful. Thing is that everytime python fails to capture Ctrl + C.
while True:
line = input()
if ('line contains Ctrl+C')
break
print(line)
print("Exiting")
I expect that after pressing Ctrl + C , program will print "Exiting" and stop execution.
The main thing there is what happens when you press Ctrl+C. It just stops. That being said, you might be able to except KeyboardInterrupt. Have you tried this?
import sys
try:
#Code Stuff Goes Here
except KeyboardInterrupt:
print(Exiting...)
sys.exit()

Python: read from stdin with "for _ in sys.stdin" requires two Ctrl+Ds to exit?

This question is specific to Python 2.7. I'm using Linux. The question is about the following 3-line python program.
import sys
for line in sys.stdin:
print line
Question 1: When I run the program and type my input, why doesn't the program print anything when I press enter? It only prints after I press Ctrl+D.
Question 2: After I press Ctrl+D, why doesn't the program exit? Pressing Ctrl+D once prints all the stuff I typed so far (as mentioned in Question 1). I have to press Ctrl+D again to exit. I thought Ctrl+D was supposed to mark the end of file of sys.stdin? But apparently no: I can type a bunch of things, press Ctrl+D to print, type a bunch of things again, press Ctrl+D again, and so on.
Question 2 (extra): When I redirect a file into the program, as opposed to typing directly into the terminal, the program does terminate properly---that is, I don't need to "end the file twice" by pressing Ctrl+D twice. How come typing into the terminal is different?
Question 3: How come this program does work as expected in Python 3? (i.e. it echoes back what I typed in every time I press enter) What changed?
I anticipate that a good answer to this question would explain what is the iterator returned by sys.stdin in a for loop, and exactly what the iterator and the Python interpreter are doing. Other websites seem to vaguely point out that "for line in sys.stdin" reads the whole file before executing the for loop, but it doesn't explain why and how that works, why it doesn't work that way in Python 3, and why I need to press Ctrl+D twice on the terminal.

My typing simulator runs in the python shell but not in real life?

I am writing a program to simulate typing and it runs in the python shell but not when double clicked any ideas?
My code is as follows:
import sys,time
def slow_text(str):
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush
time.sleep(0.1)
print("")
slow_text('Hello')
I am using python 3.5.
You're not actually calling sys.stdout.flush. That line should be:
sys.stdout.flush()
Without flushing, what's actually happening is that the script delays for some seconds with a blank console window (while the characters go into the output buffer) and then they all appear at once and the script ends and the window immediately closes, before you have a chance to see them.
That it worked in the Python shell was just a coincidence.

Categories