Pycharm variable assignment not recognized inside try block - python

try:
driver = launch_browser()
except:
print "Browser launch failed"
driver.get("http://www.example.com/")
The last line above is flagged by PyCharm with the following issue:
Local variable "driver" might be referenced before assignment
However, something like this makes the error go away:
driver = None
try:
driver = launch_browser()
except:
print "Browser launch failed"
driver.get("http://www.example.com/")
Is there a way to setup PyCharm so that it will see the assignements inside try blocks?
Secondarily, can PyCharm figure out the type based on the return value of the function (in this case launch_browser()) if it has docstrings?
BTW, code works just fine in both cases. It's just a matter of getting PyCharm to understand the assignment inside the try block without having to resort to a band-aid.
EDIT 1:
A return in the except: block fixes the problem as far as PyCharm is concerned. I was working on something else and inadvertently commented it out. Proof that coding for 16 hours straight is a really bad idea...

If launch_browser() fails, your code will error at the driver.get("http://www.example.com/") line. PyCharm is letting you know this.
The only way to avoid this is by not executing anything below the except, e.g. throwing an exception inside it, or putting everything that relies on driver inside an else block, which will only run if no exception is caught. E.g.
try:
driver = launch_browser()
except:
print "Browser launch failed"
else:
driver.get("http://www.example.com/")

Related

Selenium and Python using If statement

I am trying understand why an if else isn't working using Selenium and Python. I have tried several different variations, but I believe this should work and stubbornly, maybe blindly, keep coming back to it.
example:
if (self.driver.find_element_by_class_name('product')).text == "FEATURED PRODUCTS":
print "\nHome Pass"
else:
print "\nHome Fail"
Tried this as well
if self.driver.find_element_by_class_name("product-teaser-list").text in "Featured Products":
Each execution returns Fail and when using assert, below, the .text is found. So I know the text is found with this method.
assert "FEATURED PRODUCTS" in self.driver.find_element_by_class_name('product').text
try this following code.
if "FEATURED PRODUCTS" in self.driver.find_element_by_class_name('product').text
If this isn't working try to debug that. something white space creates an issue. however given the assert statement is passing, following should work.

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!'

PyCharm: Unreachable Code?

PyCharm is showing me that some code is unreachable within a method before the return statement is reached. I cannot help but wonder how is that even remotely possible?
def post(self):
# get the desired parameters
username = self.request.get('user')
password = self.request.get('pass')
if not self.REGEX.match(username) or not self.REGEX.match(password):
logging.debug('RegistrationHandler: Bad credentials ->', username, password)
self.fail('bad username or password')
print 'Blah' # <---- shows as UNREACHABLE ?
return # <---- shows as UNREACHABLE ?
self.fail simply calls self.response.write(things).
Update:
Yeah, when I surround it with a try/catch clause, the issue is resolved... Strange. (Note that the method doesn't always raise an exception.
I actually think this is a bug in PyCharm, thinking that fail refers to TestCase.fail, which would in fact make the code unreachable.
If I use your example, but rename fail to for example failure, the errors disappears. I'd report this bug to the friendly folks at PyCharm to see if this is in fact the case.
This code is unreachable less...
Inspection info: This inspection detects code which can not be normally reached.
import random
from typing import List, Any
while True:
x: List[Any] = list(str(random.sample(range(1001, 10000), 1)))
x.remove("[")
x.remove("]")
print(x)
check the indentation of your function and the statement/line which is unreachable.
I used it like the second function is included in the first functions' indentation
How the code should be when indentation removed
then I removed the indentation before if statement and I got the result.
.
.
.
.
.
.
.
.
You are Welcome!

Ignore exceptions thrown and caught inside a library

The Python standard library and other libraries I use (e.g. PyQt) sometimes use exceptions for non-error conditions. Look at the following except of the function os.get_exec_path(). It uses multiple try statements to catch exceptions that are thrown while trying to find some environment data.
try:
path_list = env.get('PATH')
except TypeError:
path_list = None
if supports_bytes_environ:
try:
path_listb = env[b'PATH']
except (KeyError, TypeError):
pass
else:
if path_list is not None:
raise ValueError(
"env cannot contain 'PATH' and b'PATH' keys")
path_list = path_listb
if path_list is not None and isinstance(path_list, bytes):
path_list = fsdecode(path_list)
These exceptions do not signify an error and are thrown under normal conditions. When using exception breakpoints for one of these exceptions, the debugger will also break in these library functions.
Is there a way in PyCharm or in Python in general to have the debugger not break on exceptions that are thrown and caught inside a library without any involvement of my code?
in PyCharm, go to Run-->View Breakpoints, and check "On raise" and "Ignore library files".
The first option makes the debugger stop whenever an exception is raised, instead of just when the program terminates, and the second option gives PyCharm the policy to ignore library files, thus searching mainly in your code.
The solution was found thanks to CrazyCoder's link to the feature request, which has since been added.
For a while I had a complicated scheme which involved something like the following:
try( Closeable ignore = Debugger.newBreakSuppression() )
{
... library call which may throw ...
} <-- exception looks like it is thrown here
This allowed me to never be bothered by exceptions that were thrown and swallowed within library calls. If an exception was thrown by a library call and was not caught, then it would appear as if it occurred at the closing curly bracket.
The way it worked was as follows:
Closeable is an interface which extends AutoCloseable without declaring any checked exceptions.
ignore is just a name that tells IntelliJ IDEA to not complain about the unused variable, and it is necessary because silly java does not support try( Debugger.newBreakSuppression() ).
Debugger is my own class with debugging-related helper methods.
newBreakSuppression() was a method which would create a thread-local instance of some BreakSuppression class which would take note of the fact that we want break-on-exception to be temporarily suspended.
Then I had an exception breakpoint with a break condition that would invoke my Debugger class to ask whether it is okay to break, and the Debugger class would respond with a "no" if any BreakSuppression objects were instantiated.
That was extremely complicated, because the VM throws exceptions before my code has loaded, so the filter could not be evaluated during program startup, and the debugger would pop up a dialog complaining about that instead of ignoring it. (I am not complaining about that, I hate silent errors.) So, I had to have a terrible, horrible, do-not-try-this-at-home hack where the break condition would look like this: java.lang.System.err.equals( this ) Normally, this would never return
true, because System.err is not equal to a thrown exception, therefore the debugger would never break. However, when my Debugger class would get initialized, it would replace System.err with a class of its own,
which provided an implementation for equals(Object) and returned true if the debugger should break. So, essentially, I was using System.err as an eternal global variable.
Eventually I ditched this whole scheme because it is overly complicated and it performs very bad, because exceptions apparently get thrown very often in the java software ecosystem, so evaluating an expression every time an exception is thrown tremendously slows down everything.
This feature is not implemented yet, you can vote for it:
add ability to break (add breakpoint) on exceptions only for my files
There is another SO answer with a solution:
Debugging with pycharm, how to step into project, without entering django libraries
It is working for me, except I still go into the "_pydev_execfile.py" file, but I haven't stepped into other files after adding them to the exclusion in the linked answer.

Dropping a file onto a script to run as argument causes exception in Vista

edit:OK, I could swear that the way I'd tested it showed that the getcwd was also causing the exception, but now it appears it's just the file creation. When I move the try-except blocks to their it actually does catch it like you'd think it would. So chalk that up to user error.
Original Question:
I have a script I'm working on that I want to be able to drop a file on it to have it run with that file as an argument. I checked in this question, and I already have the mentioned registry keys (apparently the Python 2.6 installer takes care of it.) However, it's throwing an exception that I can't catch. Running it from the console works correctly, but when I drop a file on it, it throws an exception then closes the console window. I tried to have it redirect standard error to a file, but it threw the exception before the redirection occurred in the script. With a little testing, and some quick eyesight I saw that it was throwing an IOError when I tried to create the file to write the error to.
import sys
import os
#os.chdir("C:/Python26/Projects/arguments")
try:
print sys.argv
raw_input()
os.getcwd()
except Exception,e:
print sys.argv + '\n'
print e
f = open("./myfile.txt", "w")
If I run this from the console with any or no arguments, it behaves as one would expect. If I run it by dropping a file on it, for instance test.txt, it runs, prints the arguments correctly, then when os.getcwd() is called, it throws the exception, and does not perform any of the stuff from the except: block, making it difficult for me to find any way to actually get the exception text to stay on screen. If I uncomment the os.chdir(), the script doesn't fail. If I move that line to within the except block, it's never executed.
I'm guessing running by dropping the file on it, which according to the other linked question, uses the WSH, is somehow messing up its permissions or the cwd, but I don't know how to work around it.
Seeing as this is probably not Python related, but a Windows problem (I for one could not reproduce the error given your code), I'd suggest attaching a debugger to the Python interpreter when it is started. Since you start the interpreter implicitly by a drag&drop action, you need to configure Windows to auto-attach a debugger each time Python starts. If I remember correctly, this article has the needed information to do that (you can substitute another debugger if you are not using Visual Studio).
Apart from that, I would take a snapshot with ProcMon while dragging a file onto your script, to get an idea of what is going on.
As pointed out in my edit above, the errors were caused by the working directory changing to C:\windows\system32, where the script isn't allowed to create files. I don't know how to get it to not change the working directory when started that way, but was able to work around it like this.
if len(sys.argv) == 1:
files = [filename for filename in os.listdir(os.getcwd())
if filename.endswith(".txt")]
else:
files = [filename for filename in sys.argv[1:]]
Fixing the working directory can be managed this way I guess.
exepath = sys.argv[0]
os.chdir(exepath[:exepath.rfind('\\')])

Categories

Resources