EOF Error in Python 2 - python-2.7

I am solving a problem on http://hackerrank.com using Python 2
The compiler is giving an error
Traceback (most recent call last):
File "/run-Lx3mHJ3G2jHRLRW9bjbX/solution.py", line 4, in
t = raw_input()
EOFError: EOF when reading a line
This is the code :
import sys
a = []
while 1:
t = raw_input()
if t=="":
break
else:
s = [i for i in t]
s.reverse()
a.append(s)
a.reverse()
for i in a:
for j in i:
sys.stdout.write(j)
sys.stdout.write('\n')
When I run it on my computer, it works fine.
Is it a problem I should report with the HackerRank interpreter or am I doing something wrong?
For sake of complete information, I already tried using "input()", "str(input())" and other possible variants.

HackerRank seems not to support the python idiom of repeating raw_input() until it gets an empty line. HackerRank apparently requires the submitted code to use the test description parameters in the header section (first line or two of input) to control the number of lines read.
Attempting to read past the last expected input line triggered a similar EOFError in my trials:
...
def main():
lines = []
line = raw_input()
while line:
lines.append(line)
line = raw_input() # line 232
...
resulted in
Status: EOFError thrown on line 232
Rewriting the input code to read just the expected number of lines was enough for the revised submission to pass. For example, for the 'Service Lane' warmup exercise in the Algorithms section:
...
first_line = raw_input()
freeway_length, testcase_count = parse_session_controls(first_line)
second_line = raw_input()
widths = parse_widths(second_line, freeway_length)
for _unused in range(testcase_count):
testcase_line = raw_input()
entrance_num, exit_num = parse_testcase(testcase_line, freeway_length)
print(measure_bottleneck(widths, entrance_num, exit_num))
...

Related

Passing stdin for cpp program using a Python script

I'm trying to write a python script which
1) Compiles a cpp file.
2) Reads a text file "Input.txt" which has to be fed to the cpp file.
3) Compare the output with "Output.txt" file and Print "Pass" if all test cases have passed successfully else print "Fail".
`
import subprocess
from subprocess import PIPE
from subprocess import Popen
subprocess.call(["g++", "eg.cpp"])
inputFile = open("input.txt",'r')
s = inputFile.readlines()
for i in s :
proc = Popen("./a.out", stdin=int(i), stdout=PIPE)
out = proc.communicate()
print(out)
`
For the above code, I'm getting an output like this,
(b'32769', None)
(b'32767', None)
(b'32768', None)
Traceback (most recent call last):
File "/home/zanark/PycharmProjects/TestCase/subprocessEg.py", line 23, in <module>
proc = Popen("./a.out", stdin=int(i), stdout=PIPE)
ValueError: invalid literal for int() with base 10: '\n'
PS :- eg.cpp contains code to increment the number from the "Input.txt" by 2.
pass the string to communicate instead, and open your file as binary (else python 3 won't like it / you'll have to encode your string as bytes):
with open("input.txt",'rb') as input_file:
for i in input_file:
print("Feeding {} to program".format(i.decode("ascii").strip())
proc = Popen("./a.out", stdin=PIPE, stdout=PIPE)
out,err = proc.communicate(input=i)
print(out)
also don't convert input of the file to integer. Leave it as string (I suspect you'll have to filter out blank lines, though)

Getting inconsistent "invalid literal for int()" error

Although this is a super common error, I haven't found a solution for this particular issue.
I have a script with a line that reads
line = int(ser.readline())
Sometimes (not everytime!) when I run this script is get this error:
Traceback(most recent call last):
File "./project.py", line 28, in <module>
line = int(ser.readline())
ValueError: invalid literal for int() with base 10:' '
When this happens, I can simply restart the script, and it works fine.
What's going on here? Is there a way to prevent this from happening?
Here's the full script, for reference. The offending code is on line 28.
#!/usr/bin/python
import time
import serial
import subprocess
# -------------function for videos-------------
def play_vid_nonblocking(num):
return subprocess.Popen(["xterm", "-fullscreen", "-e", "omxplayer", "-o", "hdmi", "-r", "/home/pi/Ligia/{:02d}.mp4".format(num)])
# -------------sensor setup-------------
ser = serial.Serial('/dev/ttyACM0', 9600)
# -----------------------------------------
num_videos = 10
i = 1
p = None
time.sleep(60)
while True:
line = int(ser.readline())
print line
if line < 750:
if p is None or p.poll() is not None:
p = play_vid_nonblocking(i)
time.sleep(60)
i = i + 1
if i > num_videos:
i = 0
else:
pass
else:
pass
else:
pass
ser.close()
#jonrsharpe above suggested the script was sometimes reading whitespace. This was fixed by adding a "Try" statement:
try:
line = int(line)

Got "ValueError: X should be a square kernel matrix" in python

I have a short script in python and I need get the exception, but only a valueError not the full content. I explain with the code:
try:
r = str(ML_engine.Create_ML_Alg_Python(sc, m))
ML_engine.updateModel('success',r,m)
return r
except Exception as inst:
ML_engine.updateModel(str(inst), -200, m)
return str(inst)
when exception occurred, in the python console view:
File "/home/sm/spark-1.6.1-bin-hadoop2.6/spark-1.6.1-bin hadoop2.6/spark-1.6.1-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
serializer.dump_stream(func(split_index, iterator), outfile)
File "/home/sm/spark-1.6.1-bin-hadoop2.6/spark-1.6.1-bin-hadoop2.6/spark-1.6.1-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream
vs = list(itertools.islice(iterator, batch))
File "/usr/local/lib/python2.7/dist-packages/spark_sklearn/grid_search.py", line 228, in fun
return_parameters=True, error_score=error_score)
File "/usr/local/lib/python2.7/dist-packages/sklearn/cross_validation.py", line 1524, in _fit_and_score
X_train, y_train = _safe_split(estimator, X, y, train)
File "/usr/local/lib/python2.7/dist-packages/sklearn/cross_validation.py", line 1585, in _safe_split
ValueError: X should be a square kernel matrix
I need only ValueError
type(inst).__name__ will help you get the error type name. Something like this:
try:
a = float('a')
except Exception as e:
print type(e).__name__
Will print ValueError.
str(inst) or inst.message will get you the message of the error (worked always for me. But if the message isn't set, then you need to figure out another way).
I think what you are trying to say is you only need the error name. So, the aptest solution for that case would be to use sys.exc_info().
Refer: https://docs.python.org/2/library/sys.html

Python csv writer "AttributeError: __exit__" issue

I have three variables I want to write in a tab delimited .csv, appending values each time the script iterates over a key value from the dictionary.
Currently the script calls a command, regex the stdout as out then assigns the three defined regex groups to individual variables for writing to .csv labeled first second and third. I get a __exit_ error when I run the below script.
/note I've read up on csv.writer and I'm still confused as to whether I can actually write multiple variables to a row.
Thanks for any help you can provide.
import csv, re, subprocess
for k in myDict:
run_command = "".join(["./aCommand", " -r data -p ", str(k)])
process = subprocess.Popen(run_command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = process.communicate()
errcode = process.returncode
pattern = re.compile('lastwrite|(\d{2}:\d{2}:\d{2})|alert|trust|Value')
grouping = re.compile('(?P<first>.+?)(\n)(?P<second>.+?)([\n]{2})(?P<rest>.+[\n])',
re.MULTILINE | re.DOTALL)
if pattern.findall(out):
match = re.search(grouping, out)
first = match.group('first')
second = match.group('second')
rest = match.group('rest')
with csv.writer(open(FILE, 'a')) as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(first, second, rest)
Edit: Requested in the comments to post entire traceback, note the line listed in traceback will not match the above code as this is not the entire script.
Traceback (most recent call last):
File "/mydir/pyrr.py", line 60, in <module>
run_rip()
File "/mydir/pyrr.py", line 55, in run_rip
with csv.writer(open('/mydir/ntuser.csv', 'a')) as f:
AttributeError: __exit__
Answer: Using the below comment I was able to write it as follows.
f = csv.writer(open('/mydir/ntuser.csv', 'a'),
dialect=csv.excel,
delimiter='\t')
f.writerow((first, second, rest))
The error is pretty clear. The with statement takes a context manager, i.e., an object with an __enter__ and an __exit__ method, such as the object returned by open. csv.writer does not provide such an object. You are also attempting to create the writer twice:
with open(FILE, 'a') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(first, second, rest)
The with ... f: is like a try...except...finally that guarantees that f is closed no matter what happens, except you don't have to type it out. open(...) returns a context manager whose __exit__ method is called in that finally block you don't have to type. That is what your exception was complaining about. open returns an object that has __exit__ properly defined and can therefore handle normal exit and exceptions in the with block. csv.writer does not have such a method, so you can't use it in the with statement itself. You have to do it in the with block following the statement, as I've shown you.

Sublime Text 2 EOFError

I'm studying Python using Sublime Text 2.
I typed just the following two statements:
usr = raw_input('input any letters: ')
print usr
After pressing CMD+B, the following error message occurred.
input any letters: Traceback (most recent call last):
File "/Users/jun/Documents/workspace/studyPython/test.py", line 1, in <module>
usr = raw_input('input any letters: ')
EOFError: EOF when reading a line
[Finished in 0.3s with exit code 1]
How can I fix it? (I'm using Python 2.7.3 in OS X 10.8.2)
The problem is that raw_input isn't getting any input when you run the file in Sublime Text 2, so Python is throwing an error.
In the console that appears (where you see the error), there isn't anywhere for you to type in your arguments. You need to run the script at the command line to make it work. At a shell prompt (in OS X, probably Terminal, found in /Applications/Utilities/Terminal.app), type the following line:
python /path/to/script/test.py
The following line then appears:
input any letters:
with a cursor at the end of the line. This is prompting you to enter your raw_input, which allows it to set the use variable. You then type some text, for example:
input any letters: this is some text
and Python will print what you just typed:
this is some text
This doesn't work in SL2, because SL2 (afaik) doesn't have a way to offer you that prompt for raw_input.