I am running someone else's code:
./run_me.sh
Traceback (most recent call last):
File "train.py", line 13, in <module>
import options
File "/Users/test/Desktop/lang-emerge/options.py", line 44
except IOError, msg: parser.error(str(msg));
^
SyntaxError: invalid syntax
I tried modifying the except block, but again I get an error:
./run_me.sh
Traceback (most recent call last):
File "train.py", line 13, in <module>
import options
File "/Users/test/Desktop/lang-emerge/options.py", line 44
except: IOError, msg: parser.error(str(msg));
^
SyntaxError: only single target (not tuple) can be annotated
The code where error is:
try: parsed = vars(parser.parse_args());
except: IOError, msg: parser.error(str(msg));
Don't know what to do to resolve the error? The msg is a keyword in python try/except blocks.
With the modified code, IOError as msg:
I get:
./run_me.sh
Traceback (most recent call last):
File "train.py", line 13, in <module>
import options
File "/Users/test/Desktop/lang-emerge/options.py", line 44
except: IOError as msg: parser.error(str(msg));
^
SyntaxError: invalid syntax
except: IOError as msg: parser.error(str(msg));
You have unnecessary colon. You should remove it: Below code is the correct one.
except IOError as msg: parser.error(str(msg));
Related
In Mutagen i read tags form an audiofile but when the tag don't exist, i get an error of course.
audio = ID3(musicfile)
print(audio['TXXX:SERIES'].text[0])
KeyError: 'TXXX:SERIES'
how to move on if tag don't exist?
i have tried:
if audio['TXXX:SERIES'].text[0] is None:
print('No series')
else:
also
if not audio['TXXX:SERIES'].text[0]:
print('No series')
else:
still gives an error.
Traceback (most recent call last):
File "D:\xxxxx\all_the_program.py", line 163, in <module>
if audio['TXXX:SERIES'].text[0] is None:
File "D:\xxxxx\venv\lib\site-packages\mutagen\_util.py", line 537, in __getitem__
return self.__dict[key]
Traceback (most recent call last):
File "D:\xxxxx\all_the_program.py", line 163, in <module>
if not audio['TXXX:SERIES'].text[0]:
File "D:\xxxxxx\venv\lib\site-packages\mutagen\_util.py", line 537, in __getitem__
return self.__dict[key]
KeyError: 'TXXX:SERIES'
You have to use try/except:
try:
print(audio['TXXX:SERIES'].text[0])
except:
print('An exception occurred')
And if you want that nothing happens when an exception occurs, just use pass:
try:
print(audio['TXXX:SERIES'].text[0])
except:
pass
You can learn more about catching exceptions / exceptions handling here: https://docs.python.org/3/tutorial/errors.html
Im trying to do a simple try except, and it is working. But I want to add some custom string at the beginning of the error message. If I just add it in print, its giving error.
import sys
try:
with open('./datatype-mapping/file.json') as rs_mapping:
data_mapping = json.load(rs_mapping)
except Exception as error:
print('CUSTOM ERROR: '+error)
sys.exit(1)
The error I got is,
Traceback (most recent call last):
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 22, in get_datatype_mapping
with open('./datatype-mapping/file.json') as rs_mapping:
FileNotFoundError: [Errno 2] No such file or directory: './datatype-mapping/file.json'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 102, in <module>
main()
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 99, in main
target_mapping()
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 39, in target_mapping
data_mapping = get_datatype_mapping()
File "c:/Users/rbhuv/Desktop/code/bqshift.py", line 26, in get_datatype_mapping
print('ERROR: '+error)
TypeError: can only concatenate str (not "FileNotFoundError") to str
But if I use just print(error) - this is working.
You need to convert error to str.
import sys
try:
int("fail")
except Exception as error:
print('CUSTOM ERROR: ' + str(error))
sys.exit(1)
This works flawlessly.
Is there a way in Python to raise an error that has another error as its cause?
In Java, you can create an instance of an exception with a cause such as in the following code
try {
throw new IOException();
} catch (IOException e) {
throw new RuntimeException("An exception occurred while trying to execute", e);
}
resulting in in this error message:
Exception in thread "main" java.lang.RuntimeException: An exception occurred while trying to execute
at thing.Main.main(Main.java:11)
Caused by: java.io.IOException
at thing.Main.main(Main.java:9)
Notice that the first exception (in the stack trace) is "caused by" the second.
This is, in my opinion, a great way to show an API user that a higher-level error occurred during a call, and the developer can debug it by looking at the lower-level exception which is the "cause" of the higher-level error (in this case the RuntimeException is caused by the IOException).
With the searches I've made, I haven't been able to find anything about having an error as the cause of another in Python. Can this be achieved in Python? How? And if not, what would be a Pythonic equivalent?
In Python it is achieved by a very similar structure:
try:
raise ValueError
except ValueError:
raise ValueError('second exception')
This will generate the following traceback:
Traceback (most recent call last):
File "main.py", line 2, in <module>
raise ValueError
ValueError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "main.py", line 4, in <module>
raise ValueError('second exception')
ValueError: second exception
Another Python feature is raise from which provide a slightly different traceback:
try:
raise ValueError
except ValueError as e:
raise ValueError('second exception') from e
Traceback:
Traceback (most recent call last):
File "main.py", line 2, in <module>
raise ValueError
ValueError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 4, in <module>
raise ValueError('second exception') from e
ValueError: second exception
Further reading:
pep-3134
this SO answer
I have the following code:
import pandas as pd
index = 2
timestamps = pd.date_range('2019-05-01', '2019-05-01')
try:
timestamp = timestamps[index]
except IndexError:
raise IndexError('index is out of timestamps.')
that results in the following being printed to the terminal
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/local/lib/python3.7/site-packages/pandas/core/indexes/datetimes.py", line 1170, in __getitem__
result = self._data.__getitem__(key)
File "/usr/local/lib/python3.7/site-packages/pandas/core/arrays/datetimelike.py", line 426, in __getitem__
val = getitem(key)
IndexError: index 2 is out of bounds for axis 0 with size 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
IndexError: index is out of timestamps.
Why is IndexError: index is out of timestamps. simply not raised in this instance, please?
It was raised. The traceback provides info about the former error which was handled during the latter. Since you catch the exception and raise another, the traceback info includes both.
It is written in the description:
During handling of the above exception, another exception occurred:
You can try and raise another type of error and see that this is the error that was raised.
Because the raise statement in except block forces a new exception to handle the exception occurred in try block.
See python documentation
I could successfully connect to reddit's servers with oauth2 some time ago, but when running my script just now, I get a KeyError followed by a NoSectionError. Code is below followed by exceptions, (The code has been reduced to its essentials).
import praw
# Configuration
APP_UA = 'useragent'
...
...
...
r = praw.Reddit(APP_UA)
Error message:
Traceback (most recent call last):
File "D:\Directory\Python\lib\configparser.py", line 843, in items
d.update(self._sections[section])
KeyError: 'useragent'
A NoSectionError occurred when handling the above exception.
"During handling of the above exception, another exception occurred:"
'Traceback (most recent call last):
File "D:\Directory\Python\Projects\myprj for Reddit, globaloffensive\oddshotcrawler.py", line 19, in <module>
r = praw.Reddit(APP_UA)
File "D:\Directory\Python\lib\site-packages\praw\reddit.py", line 84, in __init__
**config_settings)
File "D:\Directory\Python\lib\site-packages\praw\config.py", line 47, in __init__
raw = dict(Config.CONFIG.items(site_name), **settings)
File "D:\Directory\Python\lib\configparser.py", line 846, in items
raise NoSectionError(section)
configparser.NoSectionError: No section: 'useragent'
[Finished in 0.2s]
Try giving it a user_agent kwarg.
r = praw.Reddit(useragent=APP_UA)