I've the following python 2.7.3 code which I am submitting to codechef online programming contest:
case = input()
for i in xrange(0, case):
try:
l = [elem for elem in raw_input().split()]
res = int(l[0][::-1]) + int(l[1][::-1])
print int(str(res)[::-1])
except:
break
This works on my computer, even when I use input redirection and use a in.txt file for input, still it works.
But the problem is when i submit it for evaluation, I get an exception and that exception gets removed when I use raw_input for getting the value of case
case = int(raw_input())
My in.txt file is as follows:
1
23 45
My problem is that its working on my computer perfectly, what is it that the online contest site feeding at the 1st line that an exception is being raised, and further it gets rectified when I use raw_input.
Shouldn't input() also work when my 1st line is always an integer?
Most likely, the site that you're submitting the code to disables the input command. This is sometimes done as part of "sandboxing", to prevent you from running arbitrary code on their machine. E.g., they wouldn't want to let you run a script that deletes all files on their disk.
The input command is more-or-less equivalent to running eval(raw_input()), and eval can be used to do just about anything.
You say you get an exception. Exactly what kind of exception, and what is the exception message?
Related
New here and very novice in Python. I have a question about Python.
At my workplace, I have some trainings with PL/SQL, where our first task was create RPN calculator. Because I'm not that good in PL/SQL and syntax of that language is strange in my opinion, I made it in Python.
Everything worked smoothly, until a time when I was asked to create function to check if string of values are RPN. Just before that, I made simple program to check if entered values match with those in dictionary, but I stopped to Run.
AcceptedChars = ["0","1","2","3","4","5","6","7","8","9","+","-","/","*"," "]
def checking_for_rpn():
checking = str(input("Enter values for check: "))
for AcceptedCharsCheck in checking:
if not(AcceptedCharsCheck in AcceptedChars):
print("False")
return False
print("Ok")
return True
Then, I added some crazy codes from web for checking RPN and that's fricked my code.
Now, I canot run it by Run Module. Shell displays standard view when it's ready.
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())))
Ive been working on a program in Python, which cracks encrypted zip files. The problem is, part of my programs key functions doesn't work.
How my program's meant to work...
User enters in zip file name.
User enters min password length.
User enters max password length.
Program will enter a loop, where it will gen a password that is within the min & max numbers.
Program will try to open the zip with the password.
Program will then print out the password if it was successful or not.
It is the 2nd last step that my program messes up on.
Instead of stooping when the passwords match, the program continues, and then tries another password. I think this is happening because there is an error happening when it tries to open the zip. So even if the password's match, its just going straight to the "except:" statement.
Here is my code which messes up -
# Function which tries to open zip (The buggy function)
def extract(zip_name, password, number):
print("\nAttempt", number)
# Tries and opens the zip
try:
zip_name.extractall(pwd=password)
print("Success: " + password)
exit(0)
except:
print("Failed: " + password)
Can anyone please show me how to make this work. Thanks
What happens when you call exit(0)? Well, if you read the documentation for the exit built-in, then you'll see that it says:
when called, raises SystemExit with the specified exit code
so it raises an exception, but in your program this is inside a try: ... except: ... so the next thing that happens is that the exception is caught and the program prints Failed and continues.
This is why people often give the advice "don't use a bare except:" — you almost never want to catch SystemExit.
Instead you could catch the actual exception raised by zipfile when the password doesn't match, which seems to be RuntimeError. Additionally, it would improve the program if you replaced the exit(0) with something like return True, and handle success or failure at a higher level of your program.
So I have a script that isn't quite working yet but I am hoping to get it to a point where it keeps trying to connect to a server until it finally succeeds (using the paramiko library). In simplistic terms, this is what my code is like:
canConnect = False
while canConnect == False:
try:
stdin, stdout, stderr = ssh.exec_command('ps')
if stdout.read():
canConnect = True
else:
# cannot connect
time.sleep(20)
except:
# cannot connect
time.sleep(20)
Now... this would be quite basic for a simple if statement but gets more complicated because I need to use "try" and "except". If the code can connect successfully (using "ps" as a random command that returns content and will prove the server is connectable), I assume it passes into the if condition that then sets canConnect to True and stops the loop. If it cannot connect, I think Paramiko will throw an exception (I put the "else" command there just in case), but once it hits the "except", it should wait for 20 seconds and then I assume the while statement will take the code back to the beginning and start again? What I have witnessed so far is that some kind of loop is happening, but it doesn't actually appear to be attempting to connect to the server.
Also, an unrelated question, documentation is scarce but I assume Paramiko /has/ to take 3 arguments like that to perform an exec_command (regardless of variables assigned, they will take standard output In, Out, Err in that order?)? I also assume it is uncommon to assign multiple comma-delimited variables to something like that, besides lists or method calls?
I think your use of except: may be masking the real problem, as it catches all exceptions, and disregards them. That would explain the some kind of loop is happening, but it doesn't actually appear to be attempting to connect to the server behavior. consider changing that to something like:
except (paramiko.SSHException, socket.error)
I am in the process of upgrading an older legacy system that is using Biztalk, MSMQs, Java, and python.
Currently, I am trying to upgrade a particular piece of the project which when complete will allow me to begin an in-place replacement of many of the legacy systems.
What I have done so far is recreate the legacy system in a newer version of Biztalk (2010) and on a machine that isn't on its last legs.
Anyway, the problem I am having is that there is a piece of Python code that picks up a message from an MSMQ and places it on another server. This code has been in place on our legacy system since 2004 and has worked since then. As far as I know, has never been changed.
Now when I rebuilt this, I started getting errors in the remote server and, after checking a few things out and eliminating many possible problems, I have established that the error occurs somewhere around the time the Python code is picking up from the MSMQ.
The error can be created using just two messages. Please note that I am using sample XMls here as the actual ones are pretty long.
Message one:
<xml>
<field1>Text 1</field1>
<field2>Text 2</field2>
</xml>
Message two:
<xml>
<field1>Text 1</field1>
</xml>
Now if I submit message one followed by message two to the MSMQ, they both appear correctly on the queue. If I then call the Python script, message one is returned correctly but message two gains extra characters.
Post-Python message two:
<xml>
<field1>Text 1</field1>
</xml>1>Te
I thought at first that there might have been scoping problems within the Python code but I have gone through that as well as I can and found none. However, I must admit that the first time that I've looked seriously at Python code is this project.
The Python code first peeks at a message and then receives it. I have been able to see the message when the script peeks and it has the same error message as when it receives.
Also, this error only shows up when going from a longer message to a shorter message.
I would welcome any suggestions of things that might be wrong, or things I could do to identify the problem.
I have googled and searched and gone a little crazy. This is holding an entire project up, as we can't begin replacing the older systems with this piece in place to act as a new bridge.
Thanks for taking the time to read through my problem.
Edit: Here's the relevant Python code:
import sys
import pythoncom
from win32com.client import gencache
msmq = gencache.EnsureModule('{D7D6E071-DCCD-11D0-AA4B-0060970DEBAE}', 0, 1, 0)
def Peek(queue):
qi = msmq.MSMQQueueInfo()
qi.PathName = queue
myq = qi.Open(msmq.constants.MQ_PEEK_ACCESS,0)
if myq.IsOpen:
# Don't loose this pythoncom.Empty thing (it took a while)
tmp = myq.Peek(pythoncom.Empty, pythoncom.Empty, 1)
myq.Close()
return tmp
The function calls this piece of code. I don't have access to the code that calls this until Monday, but the call is basically:
msg= MSMQ.peek()
2nd Edit.
I am attaching the first half of the script. this basically loops around
import base64, xmlrpclib, time
import MSMQ, Config, Logger
import XmlRpcExt,os,whrandom
QueueDetails = Config.InQueueDetails
sleeptime = Config.SleepTime
XMLRPCServer = Config.XMLRPCServer
usingBase64 = Config.base64ing
version=Config.version
verbose=Config.verbose
LogO = Logger.Logger()
def MSMQToIAMS():
# moved svr cons out of daemon loop
LogO.LogP(version)
svr = xmlrpclib.Server(XMLRPCServer, XmlRpcExt.getXmlRpcTransport())
while 1:
GotOne = 0
for qd in QueueDetails:
queue, agency, messagetype = qd
#LogO.LogD('['+version+"] Searching queue %s for messages"%queue)
try:
msg=MSMQ.Peek(queue)
except Exception,e:
LogO.LogE("Peeking at \"%s\" : %s"%(queue, e))
continue
if msg:
try:
msg = msg.__call__().encode('utf-8')
except:
LogO.LogE("Could not convert massege on \"%s\" to a string, leaving it on queue"%queue)
continue
if verbose:
print "++++++++++++++++++++++++++++++++++++++++"
print msg
print "++++++++++++++++++++++++++++++++++++++++"
LogO.LogP("Found Message on \"%s\" : \"%s...\""%(queue, msg[:40]))
try:
rv = svr.accept(msg, agency, messagetype)
if rv[0] != "OK":
raise Exception, rv[0]
LogO.LogP('Message has been sent successfully to IAMS from %s'%queue)
MSMQ.Receive(queue)
GotOne = 1
StoreMsg(msg)
except Exception, e:
LogO.LogE("%s"%e)
if GotOne == 0:
time.sleep(sleeptime)
else:
gotOne = 0
This is the full code that calls MSMQ. Creates a little program that watches MSMQ and when a message arrives picks it up and sends it off to another server.
Sounds really Python-specific (of which I know nothing) rather then MSMQ-specific. Isn't this just a case of a memory variable being used twice without being cleared in between? The second message is shorter than the first so there are characters from the first not being overwritten. What do the relevant parts of the Python code look like?
[[21st April]]
The code just shows you are populating the tmp variable with a message. What happens to tmp before the next message is accessed? I'm assuming it is not cleared.