Error when running selected line of code in VS Code - python

I cannot run the selected block of the code in VS Code.
Given the code that works well if I run it as a whole
import numpy as np
x = np.arange(5)
print(x)
if I select the line print(x) and press Shift+Enter, it yields
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
It looks like the objects are erased from the memory as soon as the compilation is over.
Could somebody explain what is the reason and how to tackle this problem?
Thank you!

As you already know, the previous objects are erased with every execution of the code from the memory.
When you run just the print statement, it is like you would just run print(x) in a new file without defining it.
To my knowledge, this can't be changed, because the python interpreter works that way, and it creates a temporary file with the selected code and runs that. In that file are the objects not defined, and thus it raises an exception.

Related

Python traceback broken: code out of sync with what is executed?

I'm running into a strange situation simply running a script from the command-line: when I run into errors, often the traceback given contains code that makes no sense. Every line in the traceback should be a method call, but sometimes they aren't. Also, the lines referenced in the traceback don't correspond to the given error. What's happening? As an example, here is a simple error where numpy wasn't imported, but the traceback makes little sense and refers to unrelated code lines:
Traceback (most recent call last):
File "bin/train_global_model.py", line 549, in <module>
if __name__ == '__main__':
File "bin/train_global_model.py", line 236, in main
def main():
File "bin/train_global_model.py", line 407, in do_training
tb_writer=train_writer,
File "bin/train_global_model.py", line 200, in run_iteration
print(accuracy)
NameError: global name 'np' is not defined
Pay special attention to the code lines referenced.
Is python caching code that is executed somewhere but then referring to the actual file when it's tracing an exception? Running Python 2.7.13.
Python saves line numbers not the actual source code, when running programs. For tracebacks it loads the source code and shows the corresponding lines to the numbers. When the source changes, while the program is running, you get lines out of sync.

Possible to modify built-in error messages in Python? (If so, how?)

I am wondering if it is possible to edit/customize the behavior and printout of built-in errors in Python. For example, if I type:
>>> a = 1
>>> print A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined
I want the output to instead be:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined. Check capitalization.
Moreover, I want this to occur at a global level, for ALL FUTURE CODE, without having to explicitly include an exception in my code. If such a change is possible, I would assume this needs to be done at the very source or library-file level of Python. However, I am not sure where exactly to look to know if this is even possible.
I am using Python 2.7 on both Ubuntu and OSX, so help on either system would be appreciated.
(My apologies in advance if this is covered elsewhere, but searching for threads on "changing Python error messages" generally gave me topics on Exceptions, which is not necessarily my interest here. If anyone can point me to a page on this though, I'd greatly appreciate it.)
YES! There is a way to exactly what you want!
traceback.py is the program that detects errors in your code. It then gives you an explanation of what happened (creates the error message that you see.)
You can find this file in your library folder for python.
When in that file you can change the messages that it outputs when you come across an error!
Please tell me if this helped you!

Handling errors while working with code snippets

I am running a bunch of code all at once in python by copying it from my editor and pasting it into python. This code includes nested for loops. I am doing some web scraping and the program quits at different times. I suspect that this is because it doesn't have time to load. I get the following error (once again - the program scrapes different amounts of text each time):
Traceback (most recent call last):
File "<stdin>", line 35, in <module>
IndexError: list index out of range
First, what does line 35 refer to? Is this the place in the relevant inner for-loop?
Second, I think that the error might be caused by a line of code using selenium like this:
driver.find_elements_by_class_name("button")[j-1].click()
In this case, how can handle this error? What is some example code with either explicit waits or exception handling that would address the issue?
It means that [j-1] doesn't exist for a given value of j, possibly if j-1 exceeds the max number of elements in the list
You can try your code and catch an IndexError exception like this:
try:
# your code here
except IndexError:
# handle the error here
An IndexError happens when you try to access an index of a list that does not exist. For example:
>>> a = [1, 2, 3]
>>> print(a[10])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
It's difficult to say how you should handle the error without more detail.
When working with code snippets, it's convenient to have them open in a text editor and either
only copy-paste into a console the part you're currently working on so that all the relevant variables are in the local namespace that you can explore from the console, or
copy-paste a moderate-to-large chunk as a whole while having enabled automatic post-mortem debugger calling, e.g. with Automatically start the debugger on an exception Activestate recipe or IPython's %pdb magic, or
run a script as a whole under debugger e.g with -m pdb, IPython's %run or by using an IDE.

Calling a function from another file in Python

Yes, this question has been asked before. No, it did not answer my question satisfactorily.
So, I'm creating my Giraffe Program in Python first (don't ask) and I'm trying to get the user to name their giraffe.
My files are all in one package called code. In the file Main_Code, the function createGiraffe is called from code.Various_Functions. Here is my code.
import code
print("Welcome to The Animal Kingdom.")
userGiraffe = code.Various_Functions.createGiraffe()
And the code in code.Giraffes:
import code
def createGiraffe():
print("Name your giraffe.")
GiraffeName = input()
return GiraffeName
However, when I run Main_Code, it gives me this error:
Traceback (most recent call last):
File "C:\Users\Jonathan\Documents\Aptana Studio 3 Workspace\The Animal Kingdom\src\code\Main_Code.py", line 3, in <module>
userGiraffe = code.Giraffes.Giraffes.createGiraffe()
AttributeError: 'module' object has no attribute 'Giraffes'
How do I fix this? I believe that I've done everything by the book. It's all using the same package so I can call the function, I'm calling it from the right place, and the function has no syntax errors. Can anyone help with this?
Do
import code.Giraffes
before executing the offending line:
userGiraffe = code.Giraffes.Giraffes.createGiraffe()
When you call function like:
userGiraffe = code.Giraffes.Giraffes.createGiraffe()
it means you have a project in dir code with internal dir Giraffes and module Giraffes with function createGiraffe. Is this your exception?

Quit function in python program

I have a program that runs in Python, without the console present (which is to say, I've compiled it using py2exe). I want people to be able to quit from the main menu, or by a particular key-press in-game (say, Shift+Q). I'm running it, for now, in Windows, though I am working on compiling Linux/Mac versions. Pressing the X button works if there's no 'while' loop running, it seems, and that closes it correctly, otherwise it seems to 'store' the close command wait until the current loop is closed.
As for menu options, I've looked thoroughly through documentation and Stackoverflow and tried quit(), exit(), sys.exit() and every combination I can find, but every time I get:
Traceback (most recent call last):
File "alphatime.pyw", line 61177, in <module>
File "alphatime.pyw", line 53970, in place_menu
NameError: global name 'sys' is not defined
if I try sys.exit, and then:
Traceback (most recent call last):
File "alphatime.pyw", line 61177, in <module>
File "alphatime.pyw", line 53970, in place_menu
NameError: global name 'quit' is not defined
if I try just "quit()". I've heard about 'Raising' things like a need to close the program, but I'm not clear what that means (I'm new to Python) and how I would go about doing that.
So, my question is two-fold.
Firstly, is there something I can put in loops for recognizing keypresses something that will recognize the 'X' being clicked, and close?
Secondly, is there an appropriate command that will just close the program? I cannot figure out why these commands don't work, and I've had quite a few complaints from people using the program that it crashes, or they have to ctrl-alt-del it, or whatever. I believe
import os
try:
os._exit(return_code)
except:
pass
would work, but at this point, I'm not sure I'm competent enough at python to deploy it appropriately. Thanks in advance!
did you by any chance
import sys
because that should work!
NameError: global name 'sys' is not defined
Before you can use sys.exit(), you must import sys.
That's the best way to exit the program. Function names that begin with _ are considered internal, and should not be used unless you are really trying to do something weird.

Categories

Resources