I have a problem in Python (2.7) - I have a cookiecutter project that prompts for input (via CLI) and then generates my project based on that input.
One of my fields is a description, and I've seen that adding quote marks in, i.e. 'Hello this is "my" description' will cause a Syntax error when I pass it through eval:
File "/var/folders/4b/gzszrl3d5fn1q7vvv05s63vmf014cj/T/tmpnJWgqK.py", line 53
parameters = eval("{u'description': u'Hello this is "my" description'}")
SyntaxError: invalid syntax
ERROR: Stopping generation because pre_gen_project hook script didn't exit successfully
The section of code executing this is:
try:
parameters = eval("{{ cookiecutter }}")
except:
print('An error occurred!')
sys.exit(1)
My problem is the code never enters the except clause, so I have no chance to exit gracefully.
Is there any way I can handle this better?
P.S. I know I could sanitise the input using some Jinja2 filters, but am looking for a solution that lets me handle an error without altering the input.
eval("{u'description': u'Hello this is "my" description'}") is your problem.
You have to escape " between my.
eval("{u'description': u'Hello this is \"my\" description'}")
Related
I am working with library ply to make a parser for commands. Code is
def p_expr(v):
'expr : token'
... # action with token, set expr value and return
??? raise error ??? # yacc must stop parse and call p_error
def p_error(p):
print('Error!')
How to raise error?
Note that Ply does not "stop the parse" when a syntax error is encountered. It tries to do error recovery, if the grammar was built with error recovery, and as a last resort it restarts the parse as though the input had been deleted up to that point. To see this, try typing 1+2 error 3+4 into the calculator example in the Ply distribution. It will print an error message for error (because it's expecting an operator) and then restart the parse, so that it prints 7.
If you want the parser to stop when it finds an error, you'll need to raise an exception from p_error. It's generally best to define your own exception class for this sort of thing. Avoid the use of SyntaxError because Ply handles that specially in certain cases, as we'll see below.
Usually, just stopping the parser is not really what you want to do -- if you don't want to try error recovery, you should normally at least do something like throw away the rest of the input line before restarting the parse.
If you do just want to stop the parser and you raise an exception in p_error to accomplish that, then the best way to signal your own error from a parser action is to call p_error with the current token.
If you want to trigger Ply's normal error recovery procedure, you an raise SyntaxError from a parser action. However, as the manual indicates, this does not call p_error, so you'll have to do that yourself before raising the error.
If you do panic mode recovery in p_error, then you're might be out-of-luck with custom error detection. Raising SyntaxError by-passes the call p_error; while you are free to call p_error yourself, there is no mechanism to pass a new token back to the parser. (Panic mode recovery is not an optimal error recovery technique, and it is not always necessary to return a replacement token. So this paragraph might not apply.)
I'm writing a tool that sends commands to the CMD for Google Lighthouse and want to catch the error if an URL isn't valid. What exception would I use?
I'm currently trying to catch RuntimeError in the Exception when entering an invalid URL.
try:
os.system("lighthouse --quiet {} {} {} {} {} --output-path={}/{}.html ".format(DevEmuStr,throttlingVar,CacheStr,presetVar,url,reportlocation,filename))
except RuntimeError:
print("Please provide a proper URL")
Instead of "Please provide a proper URL" I still get:
Runtime error encountered: The URL you have provided appears to be invalid.
LHError: INVALID_URL
at lighthouse (C:\Users\sugar\AppData\Roaming\npm\node_modules\lighthouse\lighthouse-core\index.js:44:11)
at chromeP.then._ (C:\Users\sugar\AppData\Roaming\npm\node_modules\lighthouse\lighthouse-cli\run.js:182:12)
at process._tickCallback (internal/process/next_tick.js:68:7)
And Lighthouse just continues with the next URL
Is there another error I could catch?
Thanks to everyone that tried to help me, I finally found a way to get it.
By adding this:
lh_url_ok = os.system("lighthouse --quiet {} {} {} {} {} --output-path={}/{}.html ".format(DevEmuStr,throttlingVar,CacheStr,presetVar,url,reportlocation,filename))
if lh_url_ok >0:
print("Error")
i was able to check if the exit code was above 0 (0=no error)
No, there isn't an exception you could catch from Python.
It appears to me that "Runtime error encountered" is output printed out by lighthouse, it isn't an actual Python exception you could catch.
Python doesn't know anything about what is internally going on in the executable you start with os.system, you can just get the output and an exit code.
I don't know why I am getting a error message when i run addItem() saying:
SyntaxError: unexpected EOF while parsing
I have all my reading and writing to files closed, and I'm using raw_input functions. I think something is wrong with my readfrom() function, but I don't know what exactly.
import ast
def writeTo():
itemx=",".join(map(str,itemx))
with open("ListItemz.txt","a") as filewrite:
filewrite.write(str(itemx)+"\n")
filewrite.close()
def readfrom():
fileread=open("ListItemz.txt","r")
fr=fileread.readlines()
fr=fr[len(fr)-1]
itemx=list(ast.literal_eval(fr))
fileread.close()
itemx=[]
def addItem():
global itemx
if itemx==[]:
itemx=[]
else:
"""
about to read file:
"""
readfrom()
dowhile="y"
while dowhile =="y":
item=raw_input("please enter item discription, or barcode No. ")
if itemx!=[]:
for y in itemx:
if item==y[0] or item==y[1]:
raise TypeError("This Item is already added")
case=int(raw_input("Enter how much holds in one (1) case: "))
caseNo=int(raw_input("how many cases are there? "))
for i in stockList():
if item==i[1] or item==i[0]:
itemx+=[[i[0],i[1],case,caseNo]]
print "ITEM ADDED"
dowhile=raw_input("Do you want to add another?(Y/N) ")
"""
about to write itemx to a file:
"""
writeTo()
return itemx
the file i wrote to (ListItemz.txt) had complications so i just deleted very thing and started a fresh.
I don't think the error comes from the code above. The parsing and syntax refer to the Python parser trying to read your program, not from the reading or writing you do. As the program above is not complete - there is no main program - it's difficult to see where the error could originate. Or maybe there is a main program, but the indentation is off.
There's also this strange construct:
if itemx==[]:
itemx=[]
Is that really correct?
To try and pinpoint the problem, you can use the (under-appreciated) Python debugger (pdb). Add an import pdb at the top, and insert a line where you want to stop the program:
pdb.set_trace()
You can then do:
n<enter> to advance a line of code
p variable<enter> to see the value of a variable
c<enter> to continue at full speed
... and a lot more - see the pdb manual.
Just advance through the program till the error pops.
I have this little piece of code I wrote that isn't excepting the errors that could be thrown at it. Here's the code:
def println(stringint):
try:
print stringint
except (SyntaxError, NameError):
print "Invalid format."
I run the code from the python interpreter like this, and only like this:
>>> import pcl
>>> pcl.println("Hello")
Why aren't the errors being excepted? How can I catch the errors?
Those errors that has to do with syntax are parse level errors, which means, that are errors that take place before that particular code being interpreted.
The following arenĀ“t the same type of errors:
print("Hello) # Note the missing '"'
that
print(4/0) # Syntactically correct, but obviously an error.
Hence, syntax error can't be handled by the try -- except block.
See this answer for more detail: SyntaxError inconsistency in Python?
Your code works fine, "Hello" should raise neither an EOLError nor a NameError, because the quotes are closed, and it is a string.
Consider the following code:
try:
if True a = 1 #It's missing a colon So it's a SyntaxError!!!!!!!
except SyntaxError:
print 'hey'
You'd expect it to print hey However It raises a SyntaxError, The same error I'm trying to avoid. So Can all Exceptions be handled using a try-except block? Well If SyntaxError's were an exception why is it included in the built-in exceptions? and finally how can I fix the above piece of code so that it handles the exception properly?
Note: I know what I'm trying to do Is utterly pointless and serves no real purpose
SyntaxError is a perfectly ordinary built-in exception. It is not special in any way. Only the circumstances of when it's (usually) thrown are a bit unusual.
A syntax error means that the code featuring said error cannot be parsed. It doesn't even begin to be a valid program, hence it cannot be executed. Therefore SyntaxError exceptions are raised before the program is run, and hence can't be caught from within the program.
More specifically, this exception is raised by the parser. Because the parser runs fully before the code is executed, rather then interleaved with it, a program can't catch its own syntax errors.
The parser itself is just another program though: Code invoking the parser can catch SyntaxErrors like every other exception (because it is like every other exception). Examples of "invoking the parser" include:
compile, exec, eval
import statements
Several functions in modules like ast, tokenizer, parser, etc.
Of course you need SyntaxError as a built-in exception - what else should be raised if the compiler/parser encounters a syntax error?
You're right that this error usually happens at compile time, which is before you're able to catch it (runtime). (And how would you recover from it?)
I can think of one exception, though:
>>> try:
... eval("hello =")
... except SyntaxError:
... print("Hey! Who's using eval() anyway??")
...
Hey! Who's using eval() anyway??