Resume code execution from code.interact() in Python - python

After opening an interactive console while debugging using
code.interact(local=locals())
How can I resume code execution. I have checked the docs for the 'code' module and search stack overflow but cannot find anything.

It's the same way you exit any Python interpreter session: send an end-of-file character.
That's Ctrl-D on Linux or Ctrl-Z Enter on Windows.

If like me you always forget to hit Ctrl-D, you can wrap up your prompt in a try/except block:
try:
code.interact(local=locals())
except SystemExit:
pass

Related

Prevent Python Interpreter from Exiting if CTRL-D is pressed

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}')

How to remove "press enter to continue" when running Powershell within Python

Edited* Solution: Remove "pause".
I'm running a python script which calls upon powershell to execute a line of code:
def download():
subprocess.call('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4;pause', shell=True)
download()
The problem was that after executing, it would output "Press Enter to continue..." This interrupts the program.*in my original example I forgot to include the ";pause" which is what turned out to be what was causing the interruption in the program, as kindly pointed out by the marked answer.
Below is the fixed line of code which does not prompt "press enter to continue" after running:
def download():
subprocess.call('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4;kill $pid', shell=True)
download()
Apologies for confusion caused by the original post. Thanks for the help.
PowerShell normally exits unless you specify -NoExit at the commandline. Even then it will not include the message you are seeing unless you add a pause at the end instead. Even so, I would expect your command to look more like
'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe & {yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4}'
My guess this has more to do with Python, though I have not encountered it before...have you tried executing the PowerShell line from another commandline (cmd on Windows or bash on Linux/Mac or another favourite) to verify that you get the same result independently of Python?
Another possibility is that it is the yt-dlp tool that you are using that has the pause effect (I am not familiar with the tool). Is it a PowerShell module? Or is it something that can be run on the commandline and you don't need PowerShell as a middleman anyway? Would it have a "silent" or "-q" argument, or another more relevant argument?

Python JupyterLab: Stop the execution of a code at a line

I have a long code that sometimes I do not want to execute all of the code, but just stop at a certain line. To stop the execution of a code at a line, I do the following:
print('Stop here: Print this line')
quit()
print('This line should not print because the code should have stopped')
The right answer is only the first line should print. When I use quit(), quit , exit(), or exit both lines print. When I use import sys and then sys.exit() I get the following error message
An exception has occurred, use %tb to see the full traceback.
SystemExit
C:\Users\user\anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3351:
UserWarning: To exit: use 'exit', 'quit', or Ctrl-D. warn("To exit:
use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
How can I perform this task of stopping execution at a line?
In case you are trying to debug the code and may want to resume from where it stopped, you should be using pdb instead
print('Stop here: Print this line')
import pdb; pdb.set_trace()
print('This line should not print because the code should have stopped')
When you execute it, the interpreter will break at that set_trace() line. You will then be prompted with pdb prompt. You can check the values of variable at this prompt. To continue execution press c or q to quit the execution further. Check other useful command of pdb.
It appears that you would like to stop the code at a certain point of your choosing
To do this I found two possible ways within your constraints.
One is that you simply write
raise Exception("Finished code")
This would allow you to stop the code and raise your own exception and write whatever exception you so choose.
However, if you would like to not have any exception whatsoever then I would point you to this link: https://stackoverflow.com/a/56953105/14727419.
It seems to be an issue related to iPython, as seen here.
If you don't wish to use the solution provided there, and don't mind forcefully killing the process, you can do:
import os
os.system('taskkill /F /PID %d' % os.getpid())
For your debugging purposes it fine to use the builtin debugger pdb. The following link gives a tutorial how to set it up: Debug Jupyter
This is what I have to prevent unintentional execution of the Tests section at the bottom of the pipeline:
import pdb
# this line should capture the input, temporarily
# preventing subsequent notebook cells from being executed
pdb.set_trace()
# this line causes pdb to exit with an error, which is required
# to stop subsequent cells from execution if user fails to type
# "exit" in pdb command line and just presses the Stop button in the Notebook interface
raise Error("This line should fail to prevent cells below from being executed regardless of how pdb was exited!")

Stop Windows from closing Python

This question may have been asked a couple of times but I cannot seem to find it.
Basically I am just learning Python and I am on Windows, this means I double click the .py file and open it. This works great until an error appears, at which point Python calls exit and the window closes.
One way, of course, to get around this is to use the cmd program in Windows and run the Python program from there, however, is there a way to fix it so that my application doesn't bail out and close as soon as it hits an error if I open it from Windows Explorer?
while(True):
try:
number = input('Enter a number: ')
if(is_int(number) is False):
print('Please actually enter a number')
if(number > 0):
answer = input('Oh Noes you really want that?')
if(answer == 'yes'):
sys.exit(0);
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
input('')
In order to keep your program intact, e.g. to not introduce unwanted catch-em-all exception handling (aka pokemon handling) there are at least three options:
Use any console terminal, e.g. built-in cmd or powershell or any third-party console apps out there.
Use any IDE: pycharm, IDLE (python windows installer by default sets it up) or whatever you have capable of running python code.
Use text editor plugins for running python code. At least notepad++ and sublime text are capable of doing so.
I would recommend starting with option 1 for starters, then slowly move to option 3 for small scripts and projects, and option two for larger ones.
I you put an input function at the bottom of your script then it will hang there until you hit enter or close the command prompt. If you call an exit function put it immediately before the exit function is called. Otherwise place it at the bottom of the script.
Also I assume you have defined is_int already in your script?
What would you think it should do?
Python is drawing the window you see, if python crashes, the windows is going away.
You can run it trough cmd, or within an IDE. (like IDLE, that has some problem though when it comes to GUI)
Otherwise, add something like this at the end of the file
try:
run()
except Exception as inst:
print type(inst), inst.args
#it prints the exception
print sys.exc_traceback.tb_lineno
#if you want the line number where the error occurred in the source code
raw_input()
inst is the exception instance, you can see the type and the list of arguments.
Then with the sys module you can also see the line where the error occurred in the code.
This way every error will be handled and displayed before closing
Is this the right way?
No. You should really be using ad IDE (like Eclipse with PyDev or PyCharm).
After #SeçkinSavaşçı's extremely useful comment at the start:
The most common way is to let it wait for an input, then ignore the input and terminate the script.
Which took me a second to understand I went in search of how to do this, so first I saw to stop the script and used:
while(True):
try:
# Application code here
except:
input('')
Which worked really well to catch all errors, which unlike in PHP (which I have become comfortable with unfortunately) are all exceptions.
So the next part was to to tell me what error had occured and how to fix it, I needed a backtrace. It just so happens that the Python docs gave me the answer right here: http://docs.python.org/2/library/traceback.html#traceback-examples in an easy to see example:
exc_type, exc_value, exc_traceback = sys.exc_info()
print(traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout));
Add that above the input('') and I had my perfect error handling showing me everything I needed.
Thanks all,
Try import time and time.sleep(). Also, I recommend you to use IDLE or Geany. I've been using them and they work out well.

How to stay in the cmd window when the exception has been raised?

I have written a programme by python which is successfully tested under eclipse.Then I used pyinstaller to excute it as a .exe file. When the programme raise the exception ,the cmd window will quit immediately. I want to stay in this window to take a good look at this exception. How can I do it ? Thank you.
As Ms Turdy mentioned, you should run it in a command prompt or terminal first, if it will have the same behavior as the exe.
You can execute a python script with python -m pdb script.py and it will enter into the debugger. You run it by pressing C for continue, then it will break when it raises the exception.
That is because the python script has finished its job. You can do this:
import time
# your code
...
time.sleep(20)
This will give you 20 seconds to see the result. And after 20 s, the cmd window will remain 20 s for you to see the result. You can change the time for your requirement.
You can try raw_input to hold the screen:
import traceback
try:
# do something dangerous
except Exception, e:
print 'Error:', e
print traceback.format_exc()
raw_input('Input anything to end...')

Categories