Is there a way to catch RuntimeErrors when using os.system? - python

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.

Related

Problems with catching eval() SyntaxError using cookiecutter

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'}")

python disable error output

I created a script that connects via python-xmpp (xmpppy) to chat.euw1.lol.riotgames.com, but I get always an error, even there is none.
Here is the code:
jid=xmpp.protocol.JID('my_jid#pvp.net')
cl=xmpp.Client(jid.getDomain(),debug=[])
con=cl.connect(server=('chat.euw1.lol.riotgames.com', 5223))
if not con:
print 'could not connect!'
Again: everything works fine, but I still get this nasty error message:
An error occurred while looking up _xmpp-client._tcp.chat.euw1.lol.riotgames.com
I just wonder how I can prevent xmpppy from outputting it, I have tried several techniques like setting sys.stdout/stderr to os.devnull.
I think you can use a try/except structure to handle that problem..
try:
jid=xmpp.protocol.JID('my_jid#pvp.net')
cl=xmpp.Client(jid.getDomain(),debug=[])
con=cl.connect(server=('chat.euw1.lol.riotgames.com', 5223))
except:
print 'could not connect!'

urllib2.open giving 500 HTTPError exception even when call is successful

I am using urllib2 to access a URL and read the data. The urlopen call is in a try except block like below. I have seen other questions asked on the site saying they are encountering this 500 error but I could not find a concrete answer as to why we get this 500 exception even when the call is successful. Can anyone elaborate on that or point out ways to encounter it?
try:
data = urllib2.urlopen(url).read().split('\n')
except urllib2.HTTPError, e:
print "Could not get data with url {0} due to error code {1}.".format(url,e.code)
except urllib2.URLError, e:
print "Could not get data with url {0} due to reason {1}.".format(url,e.reason)
sys.exit(1)
HTTP Error 500 is a server error (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes). You should investigate the server side logs
You're getting a server side error.
You need to inspect the error (e) to see if there is any feedback on what is causing it. it usually has some of the actual error data from the server in it. not all servers will return error data though, sometimes it's just on the server logs.
If this is running on a daemon, or sporadically, you could write something that logs the contents of e somewhere.
You could also use pdb.set_trace() to set a breakpoint and inspect the object yourself.
also, while this line looks great:
data = urllib2.urlopen(url).read().split('\n')
it's a real pain during debugging and troubleshooting, which happens A LOT when using urllib.
i would suggest splitting it into a few lines like this
url_obj = urllib2.urlopen(url)
data = url_obj.read()
data = data.split('\n')
if you enter in a few breakpoints with pdb ( pdb.set_trace() ) you'll be able to instead each variable.
since you're not using a custom opener, i would also just use the requests library, which just wraps urllib and makes it less horrible.

Any way to save a traceback object in Python

I was looking to possibly try and save a traceback object and somehow pickle it to a file that I can access. An example of a use case for this is if I am submitting some python code to a farm computer to run and it fails, it would be nice to be able to open a session and access that traceback to debug the problem rather than just seeing a log of the traceback. I do not know if there is any sort of way to do this but thought it would be worth asking why it couldn't if so.
okay so you can use traceback.print_exception(type, value, traceback[, limit[, file]]) and save it in a text or json or you can refer to docs
if you find it helpful please mark it correct or upvote thanx..:)
Depending on how you've written your code, the try statement is probably your best answer. Since any error is just a class that inherits Python's builtin Exception, you can raise custom errors everywhere you need more information about a thrown error. You just need to rename your errors or pass in an appropriate string as the first argument. If you then try your code and use the except statement except CustomError as e, you can pull all the information you want out of e in the except statement as a regular instance. Example:
Your code would be:
def script():
try: codeblock
except Exception as e: raise Error1('You hit %s error in the first block'% e)
try: codeblock 2
except Exception as e: raise Error2('You hit %s error in the second block' % e)
try: script()
except Exception as e:
with open('path\to\file.txt','w') as outFile:
outFile.write(e)
The last part is really nothing more than creating your own log file, but you have to write it down somewhere, right?
As for using the traceback module mentioned above, you can get error information out of that. Any of the commands here can get you a list of tracebacks:
http://docs.python.org/2/library/traceback.html
On the otherhand, if you're trying to avoid looking at log files, the traceback module is only going to give you the same thing a log file would, in a different format. Adding your own error statements in your code gives you more information than a cryptic ValueError about what actually happened. If you print the traceback to your special error, it might give you still more information on your issue.

Failed to write to file but generates no Error

I'm trying to write to a file but it's not working. I've gone through step-by-step with the debugger (it goes to the write command but when I open the file it's empty).
My question is either: "How do I see what the error is so I can debug?", "What can go wrong when trying to write to a file that would cause it to behave this way?".
sqlScript = open('script-file.sql', 'a')
try:
sqlScript.write(sqlLine)
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
This should be simple but I can't seem to find an answer. Also, I apologize in advance as English is a second language.
Edit: I put a print statement just before and the string is not empty.
Edit2: I'm using python 2.6 if that factors in somehow.
Edit 3: I've found a "solution" to my error. I decided to try and run my script using IDLE instead of PyCharm and it works like a charm (pun intended). I have no clue why, but there it is. Any reason why that would happen?!
Building on Chris Morris' answer, maybe do something like this:
try:
sqlScript.write(sqlLine)
except Exception as e:
print type(e)
print str(e)
This will catch any Exception thrown (provided it's a subclass of Exception, of course) and tell you the type and the error message.
Also, it's possible to define multiple except: cases for different possible exceptions, so maybe try doing that for each exception that might be potentially thrown/raised.
The following code allows you to see what exception it is that is being thrown, and see a trace of where it originated from.
try:
sqlScript.write(sqlLine)
except:
print "Unexpected error:", sys.exc_info()[0]
raise
See http://docs.python.org/tutorial/errors.html for more info.
You have to put your cursor at the beginning of the file. You can do that with seek method:
myScript.seek(0)
See this answer: https://stackoverflow.com/a/2949648/2119117
If no exception is being tossed, I'd suspect the string variable 'sqlLine' is empty.
Did you print it before the write statement?
Are the keywords in the script in lowercase? The same thing happened to me in another db and I solved it by changing words to UPPERCASE.
Your current working directory isn't what you expect it to be and it's successfully writing to some script-file.sql in another directory. Try printing os.getcwd() and make sure it's what you expect, and look in that directory.
It happened on my linux environment but work on windows try
sqlScript = open('script-file.sql', 'a', buffering=False)
or
sqlScript = open('script-file.sql', 'a', 0)

Categories

Resources