SyntaxError: invalid syntax (try) - python

I'm writing a script to start all of my services like Admin and Managed Server using Python. When i tried executing it says "SyntaxError: Invalid Syntax(try). Please find the code below
import time
sleep=time.sleep
configFile =
"/u02/weblogic/user_projects/domains/base_domain/userConfig.dat"
pwFile = "/u02/weblogic/user_projects/domains/base_domain/userKey.dat"
while True:
try:
connect(userConfigFile=configFile,
userKeyFile=pwFile,
url='t3://my.Adminserver.com:7001')
break
except:
sleep(60)
nmConnect(userConfigFile=configFile,
userKeyFile=pwFile,
domainName='base_domain')
nmStart('ManageServer1')
exit()

The try/except block should have 4 spaces. Functions, classes, if statements, while loops, for loops and try/except block all get 4 spaces.
try:
connect(userConfigFile=configFile,userKeyFile=pwFile,url='t3://localhost:7001')
break
except:
The rest of your code which you posted has a few other things perhaps I would change.I wouldn't set up a sleep variable like that I personally would just call time.sleep(). Also don't forget while loops gets 4 spaces of indentation and so try/except blocks. I'm also not sure about the last 5 lines of code if they are part of the except clause but if they are space them in 8 times (the reason is because we need to get past the while loop + put the code in the except clause so 8 spaces). I would edit your code snippet in your question with the correct indentation and perhaps comment out what it is suppose to do and such.
import time
configFile = "/u02/weblogic/user_projects/domains/base_domain/userConfig.dat"
pwFile = "/u02/weblogic/user_projects/domains/base_domain/userKey.dat"
while True:
try:
connect(userConfigFile=configFile,
userKeyFile=pwFile,
url='t3://my.Adminserver.com:7001')
break
except:
sleep(60)
nmConnect(userConfigFile=configFile,
userKeyFile=pwFile,
domainName='base_domain')
nmStart('ManageServer1')
exit()

A SyntaxError is at, or before, the ^ symbol. So the error is going to be before the try: itself -- maybe a missing parenthesis on a previous line, maybe try is not indented correctly -- we cannot tell because you have elided all the previous code, but that's where you should look.

Related

python-try block does the same thing whether the condition it's false or true

I have this code:
try:
condition1==True
condition2==True
condition2==True
print("ok")
except:
print("no")
I am absolutely certain that condition2 is not True but is False. but still i get printed "ok", same thing happens even if i replace condition2==True with condition2==False
I've tried several times, I've done more tests using other methods. I even thought it might be a bug in the Python version I use because it's absurd.How is it possible? what could this be due to?
EDIT: if I use an IF statement , it works!!!
Python's try-except blocks do not work with conditions like that. Instead, a try block will try to execute a piece of code unless it runs into some exception along the way. If it does so, the except block will be activated and code inside it will be executed.
Essentially: conditions don't matter for try-except blocks.
This is a sample:
a = 100
b = 0
try:
my_var = a/b
except Exception as e:
print(e)
try running it, see what error you get!

python try statement or if statement

Hello everyone I have my code almost done but I'm trying to add in some sort of check to avoid errors. But I'm not really understanding what statement would be better to use to test the code. I know there are a few options of either using a loop, if-statement, or try. But here is the code in regards to doing captcha. I need it to run the first set of code which if the captcha doesn't pop up I continue on. But if the captcha does pop up solve it then continue on.
Some times captcha doesnt appear and if I run the whole set of code I get an error because we are expecting captcha to pop up.
Or if the captcha does appear to solve it which would.
I would really appreciate any help please as I'm not sure the right statement to use.
try should be used when something would return an error and would otherwise cause your program to stop/crash. An example of this would be:
try:
import pandas
except:
print("Unable to import pandas. Module not installed")
In this example your program will attempt to import the pandas module. If this fails it will then print out a line of text and continue running.
if statements are used to decided when to do something or not based on the returned logic. The key difference is that logic IS returned and not an error.
if x > 10:
print("This is a large number")
else:
print("This is a small number")
With this example, if 'x' did not exist it would produce an error, no more code will be executed, and the program will crash. The main difference between IF and TRY is whether logic is returned as true/false or is something just plains fails.
With your specific example it is important to know if the captcha appearing or not will break your code. Does the logic boil down to captcha = false or does captcha not exist at all and logic fails entirely?
Q: How do you define sometimes captcha doesn't appear (1%, 20%, 50%, ...)?
A: Maybe 5% of the time captcha doesn't appear.
In this case, I prefer to use Exception handling: do stuff and if something goes wrong, fix it
try:
# > 95% of the time the code below works when the captcha appears
except SomeException:
# < 5% of the time the code is called when the captcha doesn't appear
IMHO, you have not really 2 different codes: you have one and a fallback solution, it's really different than:
if x % 2:
...
else:
...

Re-running a python code with a while loop

How could I write a piece of code that recognizes if the any type of error has occurred and if it does the code just runs on a loop. What would be a function that I would place in <some error occurs> so it recognizes any error 0utput and re runs the code within 10 seconds.
while True:
<all your code>
if <some error occurs>:
time.sleep(10)
continue
Simply use try...except
while True:
try:
<all_your_code>
except:
time.sleep(10)
continue
Read this for better understanding: https://www.programiz.com/python-programming/exception-handling

Why does it work differently even though it's almost the same code in python try except?

The question I want to solve is to input two numbers and output the sum until the user finishes.(until the user inputs ctrl+d) Of course, I can solve the problem using sys.stdin, but I want to solve it using while.
The two codes below are my codes, the first one works well, but the second one doesn't work well. I don't know the difference between two codes. If anybody knows about the reason, please explain why..
from sys import stdin
# in this code, when I input ctrl d, program is finished
try:
while True:
a,b = map(int, stdin.readline().split())
print(a+b)
except:
exit()
from sys import stdin
# in this code, when I input ctrl d, 0 is printed out
try:
while 1:
print(sum(map(int, stdin.readline().split())))
except:
exit()
readline() doesn’t fail at EOF; it just returns an empty string. Splitting an empty string is fine. mapping int across an empty list is fine. Summing an empty iterable is fine (and results in zero).
In the first version, it’s the a, b unpacking that fails, but there’s no way to tell the difference when you throw away all the exception information and catch an overly broad class of exceptions at the same time.
Never use except; use except Exception to avoid catching low-level flow control exceptions. And if you feel the need to catch an exception you will otherwise ignore, consider logging the fact that you caught it for debugging purposes.
If you want to use sys.stdin, a for loop is better (line will continue to end with \n):
for line in stdin:
print(sum(map(int, line.split())))
If you want to use a while loop, input is better:
while True:
try:
line = input()
except EOFError:
break
print(sum(map(int, line.split())))

why do we use 'pass' in error handling of python?

It is conventional to use pass statement in python like the following piece of code.
try:
os.makedirs(dir)
except OSError:
pass
So, 'pass' bascially does not do anything here. In this case, why would we still put a few codes like this in the program? I am confused. Many thanks for your time and attention.
It's for the parser. If you wrote this:
try:
# Code
except Error:
And then put nothing in the except spot, the parser would signal an error because it would incorrectly identify the next indentation level. Imagine this code:
def f(x):
try:
# Something
except Error:
def g(x):
# More code
The parser was expecting a statement with a greater indentation than the except statement but got a new top-level definition. pass is simply filler to satisfy the parser.
This is in case you want the code to continue right after the lines in the try block. If you won't catch it - it either skips execution until it is caught elsewhere - or fails the program altogether.
Suppose you're creating a program that attempts to print to a printer, but also prints to the standard output - you may not want it to file if the printer is not available:
try:
print_to_printer('hello world')
except NoPrinterError:
pass # no printer - that's fine
print("hello world")
If you would not use a try-catch an error would stop execution until the exception is caught (or would fail the program) and nothing would be printed to standard output.
The pass is used to tell the program what to do when it catches an error. In this particular case you're pretty much ignoring it. So you're running your script and if you experience an error keep going without worrying as to why and how.
That particular case is when you are definite on what is expected. There are other cases where you can break and end the program, or even assign the error to a variable so you can debug your program by using except Error as e.
try:
os.makedirs(dir)
except OSError:
break
or:
try:
os.makedirs(dir)
except OSError as e:
print(str(e))
try:
# Do something
except:
# again some code
# few more code
There are two uses of pass. First, and most important use :- if exception arises for the code under try, the execution will jump to except block. And if you have nothing inside the except block, it will throw IndentationError at the first place. So, to avoid this error, even if you have nothing to do when exception arises, you need to put pass inside except block.
The second use, if you have some more code pieces after the try-except block (e.g. again some code and few more code), and you don't put pass inside except, then that code piece will not be executed (actually the whole code will not be executed since compiler will throw IndentationError). So, in order to gracefully handle the scenario and tell the interpreter to execute the lines after except block, we need to put pass inside the except block, even though we don't want to do anything in case of exception.
So, here pass as indicated from name, handles the except block and then transfers the execution to the next lines below the except block.

Categories