Python: How go to next statement when "Unsuccessful command:"occur - python

i have the following command of:
testing = plateX = g_o.getresults(g_o.Phases[0], g_o.ResultTypes.NodeToNodeAnchor.X, 'node')
it is not working in "Phases[0]" when it's 0 to 2 which gives the following error:,
plxscripting.plx_scripting_exceptions.PlxScriptingError: Unsuccessful command:
The command did not deliver any results
but will work from "Phases[3]" from 3 onward to whatever number it is. However in my script the x value in "Phases[x]" is different in every case, what i want is to test the x value until it worked without error...
So I'm guessing something like this:
for phase in g_o.Phases[0:]:
try:
testing = plateX = g_o.getresults(phase, g_o.ResultTypes.NodeToNodeAnchor.X, 'node')
except ???:
pass
but What should I put in the "???"? Or is there some other way to do this?
Thanks in advance..

Use the type of error listed in the traceback. In the example error message you provided, this is a PlxScriptingError. So:
except PlxScriptingError:

Related

Try/Except not working with BeautifulSoup

I am trying to loop over a series of pages and extract some info. However, in certain pages some exceptions occur and I need to deal with them. I created the following function to try to deal with them. See below:
def iferr(x):
try:
x
except (Exception, TypeError, AttributeError) as e:
pass
I intend to use as part of code like this:
articles = [[iferr(dp[0].find('span', class_='citation')),\
iferr(dp[0].find('div', class_='abstract')),\
iferr(dp[0].find('a', rel='nofollow')['href'])] for dp in data]
The idea is that if, for example, dp[0].find('a', rel='nofollow')['href'] leads to an error (fails), it will simply ignore it (fill it with a blank or a None).
However, whenever an error/exception occurs in one of the three elements it does not 'pass'. It just tells me that the error has occurred. There errors it displays are those I listed in the 'except' command which I assume would be dealt with.
EDIT:
Per Michael's suggestion, I was able to see that the order in which iferr processes what is going on would always prompt the error before he try. So I worked on workaround:
def fndwoerr(d,x,y,z,h):
try:
if not h:
d.find('x',y = 'z')
else:
d.find('x',y = 'z')['h']
except (Exception, TypeError, AttributeError) as e:
pass
...
articles = [[fndwoerr(dp[0],'span','class_','citation',None),\
fndwoerr(dp[0],'div','class_','abstract',None),\
fndwoerr(dp[0], 'a', 'rel','nofollow','href')] for dp in data]
Now it runs without prompting an error. However, everything returned becomes None. I am pretty sure it has to do with he way the parameters are entered. y should not be displayed as a string in the find function, whereas z has. However, I input both as string when i call the function. How can I go about this?
Example looks a bit strange, so it would be a good idea to improve the question, so that we can reproduce your issue easily. May read how to create minimal, reproducible example
The idea is that if, for example, dp[0].find('a',
rel='nofollow')['href'] leads to an error (fails), it will simply
ignore it (fill it with a blank or a None).
What about checking if element is available with an if-statement?
dp[0].find('a', rel='nofollow').get('href']) if dp[0].find('a', rel='nofollow') else None
or with walrus operator from python 3.8:
l.get('href']) if (l:=dp[0].find('a', rel='nofollow')) else None
Example
from bs4 import BeautifulSoup
soup = BeautifulSoup('<h1>This is a Heading</h1>', 'html.parser')
for e in soup.select('h1'):
print(e.find('a').get('href') if e.find('a') else None)

Why my code won't run when I'm using def?

So, I started python 2 weeks ago.
Something important bugs me, what I just don't understand.
When I have functions why my code stop running? Without defs it's working.
In my example I can't call just kezdo(), because i get an empty console.
Process finished with exit code 0
Anyone can explain it with my example code?
def kerdes(self):
self.open1 = self.open("kerdesek.txt")
self.open2 = self.open1.read()
print(self.open2)
return kezdo(self)
def kezdo(self):
print(self.open2)
user = int(input("valasz egy kerdest: "))
kerdesek = self.open2
valaszok = ("egyvalasz", "ketvalasz")
kv = {kerdesek[user]: valaszok[user]}
print(kv)
if I add kezdo()
then I get an error:
Error: kezdo() missing 1 required positional argument: 'self'
Thanks!
you should call the functions. like this:
kerdes()
kezdo()
I can only take a guess based on the limited information but it appears as if you are defining these methods (kezdo() and kerdes()) in some class.
In that case, you need to use self when calling these methods, or Python won't know what you mean.
It needs to be something along the lines of:
def kerdes(self):
self.open1 = self.open("kerdesek.txt")
self.open2 = self.open1.read()
print(self.open2)
return self.kezdo(self)
# ^^^^
# You need to use self here.

How to run ipython script in python?

I'd like to run ipython script in python, ie:
code='''a=1
b=a+1
b
c'''
from Ipython import executor
for l in code.split("\n"):
print(executor(l))
that whould print
None
None
2
NameError: name 'c' is not defined
does it exists ? I searched the doc, but it does not seems to be (well) documented.
In short, depending on what you want to do and how much IPython features you want to include, you will need to do more.
First thing you need to know is that IPython separates its code into blocks.
Each block has its own result.
If you use blocks use this advice
If you don't any magic IPython provides you with and don't want any results given by each block, then you could just try to use exec(compile(script, "exec"), {}, {}).
If you want more than that, you will need to actually spawn an InteractiveShell-instance as features like %magic and %%magic will need a working InteractiveShell.
In one of my projects I have this function to execute code in an InteractiveShell-instance:
https://github.com/Irrational-Encoding-Wizardry/yuuno/blob/master/yuuno_ipython/ipython/utils.py#L28
If you want to just get the result of each expression,
then you should parse the code using the ast-Module and add code to return each result.
You will see this in the function linked above from line 34 onwards.
Here is the relevant except:
if isinstance(expr_ast.body[-1], ast.Expr):
last_expr = expr_ast.body[-1]
assign = ast.Assign( # _yuuno_exec_last_ = <LAST_EXPR>
targets=[ast.Name(
id=RESULT_VAR,
ctx=ast.Store()
)],
value=last_expr.value
)
expr_ast.body[-1] = assign
else:
assign = ast.Assign( # _yuuno_exec_last_ = None
targets=[ast.Name(
id=RESULT_VAR,
ctx=ast.Store(),
)],
value=ast.NameConstant(
value=None
)
)
expr_ast.body.append(assign)
ast.fix_missing_locations(expr_ast)
Instead doing this for every statement in the body instead of the last one and replacing it with some "printResult"-transformation will do the same for you.

Running a function to mirror an image in python

I keep trying to run this function:
def flipPic():
#Set up source picture
barbf=getMediaPath("barbara.jpg")
barb=makePicture(barbf)
#Now, for the mirroring
mirrorPoint=219
for X in range(0,mirrorPoint):
for Y in range(0,291):
pleft=getPixel(barb,X,Y)
pright=getPixel(barb,Y,mirrorPoint + mirrorPoint - 1 - X)
setColor(pright,(getColor(pleft)))
show(barb)
return(barb)
However, an error comes up on this line:
barb=makePicture(barbf)
It says:
Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.
I'm not sure what the issue is as it is written the same way that is in my textbook.
I am still learning how to program in python, is there something I doing wrong?
I'm not sure what library you are using but this is a simple call in Pillow. The commands are these:
out = im.transpose(Image.FLIP_LEFT_RIGHT)
out = im.transpose(Image.FLIP_TOP_BOTTOM)
Taken from this chapter in the docs.

Python unbound local error on one machine but not on another

I get "UnboundLocalError: local variable 's' referenced before assign" in python script on one machine but not on another where the script runs OK. Both machines are on Windows 7 and use Python 2.7.3. Any suggestions what could be the reason for this behaviour? Thank you.
Here's the code that causes the error:
with open(self.temp_dir + test + ".log",'r') as log:
for line in log:
if "INPUT_SENTENCE" in line:
match = patternInput.match(line)
inputSentence = match.group(1).lower()
if inputSentence in self.testToDiagDict[test]:
continue
self.testToDiagDict[test][inputSentence] = []
if "STATS" in line:
if "Input Sentences" in line:
inputSentences = patternValue.findall(line)
self.testToDiagDict[test][inputSentence].append(inputSentences[0])
And the trace:
File "C:\X\Y\X\script.py", line 90, in extract_data
if "Input Sentences" in line:
UnboundLocalError: local variable 'inputSentence' referenced before assignment
The problem is on this line:
self.testToDiagDict[test][inputSentence].append(inputSentences[0])
There is no inputSentence in that scope
So the code might have worked on one machine because this if statement
if "INPUT_SENTENCE" in line:
evaluated to true, but in the case that it doesn't, that is when you get that error. I can't suggest a fix because I don't know what the rest of your code looks like or what you are trying to accomplish, but the much I have pointed out should allow you to reevaluate your design
Perhaps as #inspectorG4dget says - you have a different codepath somewhere. Here is a simple example that could cause your error
def f():
if machine1:
s = 1
else
S = 2
print s
If you would show the code, it would probably take just a few seconds to find

Categories