I'm working with Python 2.7 and PyGTK 2.24. I am working with the following tutorial. Please read it for code context.
http://www.pygtk.org/pygtk2tutorial/sec-PackingDemonstrationProgram.html
The bottom block of code (reprinted below) is throwing the following error when I type it in (verbatum):
if __name__ =="__main__":
if len(sys.argv) != 2:
sys.stderr.write("usage: packbox.py num, where num is 1, 2, or 3.\n")
sys.exit(1)
PackBox1(string.atoi(sys.argv[1]))
main()
usage: packbox.py num, where num is 1, 2, or 3.
Traceback (most recent call last): File "C:/GTKTutorial/packbox.py",
line 161, in
sys.exit(1) SystemExit: 1
Additionally, if I change the code to the following to overcome the first error, I get the next error message:
if __name__ =="__main__":
if len(sys.argv) != 1:
sys.stderr.write("usage: packbox.py num, where num is 1, 2, or 3.\n")
sys.exit(1)
PackBox1(string.atoi(sys.argv[1]))
main()
Traceback (most recent call last): File "C:/GTKTutorial/packbox.py",
line 162, in
PackBox1(string.atoi(sys.argv[1])) IndexError: list index out of
range
What is wrong? How do I fix the code so I can work with the tutorial>
You need to call it from the command line with packbox.py 1, packbox.py 2, or packbox.py 3.
This will result in there being two arguments (the name of the program and the first thing you pass to it), so you won't trigger the sys.exit(1), and argv[1] will be a valid index access.
To run PackBox.py directly from IDLE,
REPLACE:
if __name__ =="__main__":
if len(sys.argv) != 2:
sys.stderr.write("usage: packbox.py num, where num is 1, 2, or 3.\n")
sys.exit(1)
PackBox1(string.atoi(sys.argv[1]))
main()
WITH:
if __name__ == "__main__":
packbox = PackBox1(3)
main()
To see all three example widget arrangements, substitute argument (3) with arguments (1) & (2). Click on X to exit the window; the Quit buttons aren't connected in this code.
Related
I want to print an error's line number and error message in a nicely displayed way. The follow is my code, which uses linecache:
import linecache
def func():
if xx == 1:
print('ok')
try:
func()
except:
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print_('ERROR - (LINE {} "{}"): {}'.format(lineno, line.strip(), exc_obj))
However, this only gives where the func() is called:
ERROR - (LINE 8 ""): name 'xx' is not defined
Is there a way to print the line number where the error actually occured, which should be Line 4? Or even better, can I print Line 8 and then trace back to line 4? For example, if I do not use try - except, the code:
def func():
if xx == 1:
print('ok')
func()
will give me the following error message, which is much better to locate the error:
File "<input>", line 5, in <module>
File "<input>", line 2, in func
NameError: name 'xx' is not defined. Did you mean: 'xxx'?
You can use traceback and sys modules to get advanced traceback output like you are wishing for.
Here is an example:
import traceback
import sys
def func():
zeroDivide = 1 / 0
try:
func()
except Exception:
print(traceback.format_exc()) # This line is for getting traceback.
print(sys.exc_info()[2]) # This line is getting for the error type.
Output will be:
Traceback (most recent call last):
File "b:\abc\1234\pppp\main.py", line 10, in <module>
func()
File "b:\abc\1234\pppp\main.py", line 7, in func
zeroDivide = 1 / 0
ZeroDivisionError: division by zero
You can use the traceback module to get the line number of the error,
import traceback
def function():
try:
# code
except:
tb_list = traceback.extract_tb(sys.exc_info()[2])
line_number = tb_list[-1][1]
print("An error occurred on line:", line_number)
You can use the traceback.extract_tb() function. This function returns a list of traceback objects, each of which contain information about the stack trace. The last element of this list, tb_list[-1], holds information about the line where the exception occurred. To access the line number, you can use the second element of this tuple, tb_list[-1][1]. This value can then be printed using the print() function.
To get the line number as an int you can get the traceback as a list from traceback.extract_tb(). Looking at the last item gives you the line where the exception was raised:
#soPrintLineOfError2
import sys
import traceback
def func():
if xx == 1:
print('ok')
try:
func()
except Exception as e:
tb = sys.exc_info()[2]
ss = traceback.extract_tb(tb)
ss1 = ss[-1]
print(ss1.line)
print(ss1.lineno)
Output:
if xx == 1:
6
def is_table(tab):
if len(tab) != 3:
return False
valid = (-1, 0, 1)
for a in range(0, 3):
if len(tab[a]) != 3:
return False
for b in range(0, 3):
if tab[a][b] not in valid:
return False
return True
When I try to run is_table(((0,0,0),(0,0,0),(0,0,0))) on console, I get this error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'is_table' is not defined
Can anyone explain why? My function is clearly defined, but it still doesn't run on console.
The python console dont know about your files functions. First, edit your file name, removing any space, e.g., jogo_do_galo.py (or another name, like jogo_do_mengao).
Open the python console, and try:
>>> from jogo_do_galo import *
>>> tab = ((True, 0, 0), (0, 0, 0), (0, 0, 0))
>>> eh_tabuleiro(tab)
This will work.
Did you define the function inside the console, or in a separate file?
If you defined the function in a separate file, you'll need to run the file before the function will be recognized by the console.
Found an answer. Right-clicked on file name, settings, run on console.
during tests it's showing the error message:
Traceback (most recent call last):
File "tictactoe/tictactoe.py", line 10, in <module>
coordinates = input("Enter the coordinates: ")
EOFError: EOF when reading a line
I can't image what is causing this problem. The code is:
c = True
while c:
coordinates = input("Enter the coordinates: ") # <-- line 10 is this one
if coordinates == '':
print("Coordinates should be from 1 to 3!")
continue
elif len(coordinates) < 3 or len(coordinates) > 3:
print("Coordinates should be from 1 to 3!")
continue
Thanks for support
Your test probably runs the code non-interactively. If you are creating the test in Python, try using subprocess.PIPE so that you can communicate with the subprocess. Without a valid stdin, the program will throw this error, which (should) cause your test to fail.
I have write code in Python 3 in the following format :
def function1()
def function2()
def function3()
def main()
Then I call the main :
main()
The function eval() it's into my main() also.
The purpose of my code is to getting two expressions and returns whether they are equals or not.
For example :
answer = """ A ← A * 3"""
my_input = """ A ← 3 * A"""
Comparing these expressions the result must be "Equals" ( or True ).
I'm getting the error below :
Traceback (most recent call last):
File "my_path", line 218, in <module>
main()
File "my_path", line 200, in main
if eval(a) == eval(b) and eval(c) == eval(d) :
File "<string>", line 2
^
SyntaxError: unexpected EOF while parsing
Do I need to import something ?
Or to re-arrange the functions ?
I'm here to understand, not to solve the issue.
Thanks.
I'm working on a python script that need from the user to add an argument on the command line to call the script. The script is
#!/usr/bin/env python
import sys
if len(sys.argv) == 1:
sys.exit("Error : argument expected.")
print("coucou")
a = ['SDK', 'DESKTOP', 'DFEM', 'COMMAND', 'TOK', 'DESKTOPONLY']
z = a.count(sys.argv[1]
if z == 0:
sys.exit("Error : argument invalid.")
print (sys.argv[1])
and the error is
File "./test.py", line 10
if z == 0:
^
SyntaxError: invalid syntax
Can anybody help me ? :) I'm just starting python, and it's driving me crazy...