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.
Related
In trying to solve some errors I am having I would like VS Code debugger to hold my hand and take from module to module, line by line so I can see how the code works. This works as expected if I create two .py files and have code from one call a function from the other.
So if I have one file have the code:
def printer(text):
print(text)
and the second one just say:
from first_file import printer
printer('Hello')
when I put a break point on line printer('Hello') of the second file then, when the code stops there, I press F11, it will open the 1st file and I can continue pressing F11 to go on line by line.
This does not seem to happen with my current code which uses a parameter tuner from scikit-learn, namely GridSearchCV. If I put a break point on the line of code which calls the .fit method for this tuner, when the code pauses there and I press F11 it will just carry on and not walk me through the scikit-learn jungle.
Is there a way to make this happen? Some obscure setting that my googling has not revealed?
Could you try to add "justMyCode": false in the launch.json file? like this:
Otherwise, the debugger will only walk through the codes written by the user.
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.
Background
Consider the following minimal example:
When I save the following script and run it from terminal,
import time
time.sleep(5)
raise Exception
the code will raise an error after sleeping five seconds, leaving the following traceback.
Traceback (most recent call last):
File "test/minimal_error.py", line 4, in <module>
raise Exception
Exception
Now, say, I run the script, and during the 5-second-sleep, I add a line in the middle.
import time
time.sleep(5)
a = 1
raise Exception
After the python interpreter wakes up from the sleep and reaches the next line, raise Exception, it will raise the error, but it leaves the following traceback.
Traceback (most recent call last):
File "test/minimal_error.py", line 4, in <module>
a = 1
Exception
So the obvious problem is that it doesn't print the actual code that caused the error. Although it gives the correct line number (correctly reflecting the version of the script that is running, while understandably useless) and a proper error message, I can't really know what piece of code actually caused the error.
In real practice, I implement one part of a program, run it to see if that part is doing fine, and while it is still running, I move on to the next thing I have to implement. And when the script throws an error, I have to find which actual line of code caused the error. I usually just read the error message and try to deduce the original code that caused it. Sometimes it isn't easy to guess, so I copy the script to clipboard and rollback the code by undoing what I've written after running the script, check the line that caused error, and paste back from clipboard.
Question
Is there any understandable reason why the interpreter shows a = 1, which is line 4 of the "current" version of the code, instead of raise Exception, which is line 4 of the "running" version of the code? If the interpreter knows "line 4" caused the error and the error message is "Exception", why can't it say the command raise Exception raised it?
I'm not really sure if this question is on-topic here, but I don't think I can conclude it off-topic from what the help center says. It is about "[a] software [tool] commonly used by programmers" (the Python interpreter) and is "a practical, answerable problem that is unique to software development," I think. I don't think it's opinion-based, because there should be a reason for this choice of implementation.
(Observed the same in Python 2.7.16, 3.6.8, 3.7.2, and 3.7.3, so it doesn't seem to be version-specific, but a thing that just happens in Python.)
The immediate reason is that Python re-opens the file and reads the specified line again to print it in error messages. So why would it need to do that when it already read the file in the beginning? Because it doesn't keep the source code in memory, only the generated byte code.
In fact, Python will never hold the entire contents of the source file in memory at one time. Instead the lexer will read from the file and produce one token at a time, which the parser then parses and turns into byte code. Once the parser is done with a token, it's gone.
So the only way to get back at the original source code is to open the source file again.
I think it a classic problem which is described here.
Sleep use os system call to pause execution of that thread.
I made this small program :
I wanna know how to automatically call it, so that when I open the .py it shows up immediatly.
Please understand that I am a beginner in Python.
The right way to do this is to add the following statement in the end of the file:
if __name__ == "__main__":
table_par_7()
Explanation
This will ensure that if you open the file directly (and thus makes it the main file), the function will run, but if another python file imports this file (thus this file isn't the main one), it wont run.
You can call it like this:
# Add this lines at the end of your code
table_par_7()
If you mean:- (1) When you will run the .py file, how to call it. Then the answer is, you will have to write the name of function and press ENTER to execute it.
(2) When you will open the .py file from any folder, is it possible to print final result. The the answer is a big NO. This is because using def in any program is just a keyword to create function. It do not have any property by which it will execute by its own. It must be called by the system which is known as system call.
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?