EOFError: EOF when reading a line - in tic-tae-toe - Python - python

during tests it's showing the error message:
Traceback (most recent call last):
File "tictactoe/tictactoe.py", line 10, in <module>
coordinates = input("Enter the coordinates: ")
EOFError: EOF when reading a line
I can't image what is causing this problem. The code is:
c = True
while c:
coordinates = input("Enter the coordinates: ") # <-- line 10 is this one
if coordinates == '':
print("Coordinates should be from 1 to 3!")
continue
elif len(coordinates) < 3 or len(coordinates) > 3:
print("Coordinates should be from 1 to 3!")
continue
Thanks for support

Your test probably runs the code non-interactively. If you are creating the test in Python, try using subprocess.PIPE so that you can communicate with the subprocess. Without a valid stdin, the program will throw this error, which (should) cause your test to fail.

Related

SyntaxError: unexpected EOF while parsing -Python

I am using the concept of priority scheduling to create a program that should take two inputs, number of incoming packets, and the priority string for the incoming packets. For example, for input “4” and “HLHH'', the order of outgoing packets should be ``0 2 1 3''.
When i run the program i keep getting this error:
Input:4 HLHH
Traceback (most recent call last):
File "schedule.py", line 71, in <module>
main()
File "schedule.py", line 62, in main
inputStr=input("Input:")
File "<string>", line 1
4 HLHH
^
SyntaxError: unexpected EOF while parsing
Here is my source code :
import re
#Used to set the priorities for initial buffer
def setPriorityForBuffer(priorityStr,priorityList):
counter=0
outgoingPkt=[]
#Set priority for H first
for i in range(0,3):
if priorityStr[i]=='H':
outgoingPkt.append(priorityList[counter])
counter+=1
else:
outgoingPkt.append('NA')
#Set priority for L next
for i in range(0,3):
if outgoingPkt[i]=='NA':
outgoingPkt[i]=priorityList[counter]
counter+=1
return outgoingPkt
def getPriority(numPackets,priorityStr):
outputStr = " "
outgoingPkt=[]
priorityList=[]
for i in range(0,numPackets):
priorityList.append(str(i))
if numPackets<=0:
return 'Wrong input: the number of packets must be greater than 0.'
elif numPackets!=len(priorityStr):
return 'Wrong input: the number of packets is wrong.'
else:
pattern = re.compile('^[LH]+$')
if not re.search(pattern, priorityStr):
return 'Wrong input: the priority must be H or L'
if numPackets==3:
outgoingPkt=setPriorityForBuffer(priorityStr,priorityList)
elif numPackets>3:
#For first 3 packets
outgoingPkt=setPriorityForBuffer(priorityStr,priorityList)
#For remaining packets
counter=3
#Set priority for H first
for i in range(3,len(priorityStr)):
if priorityStr[i]=='H':
outgoingPkt.append(priorityList[counter])
counter+=1
else:
outgoingPkt.append('NA')
#Set priority for L next
for i in range(3,len(priorityStr)):
if outgoingPkt[i]=='NA':
outgoingPkt[i]=priorityList[counter]
counter+=1
for i in outgoingPkt:
outputStr=outputStr+i+" "
return outputStr
def main():
#Get input from user
inputStr=input("Input:")
inputList=inputStr.split(" ")
numPackets=int(inputList[0])
priorityStr=inputList[1]
#Call function and print outgoingpacket string
print("Output:",getPriority(numPackets,priorityStr))
#Driver code
main()
any help is appreciated thanks

error using pipes in python using os.pipe() and using os.fork()

So I made a simple piece of code to add 1 to a value. I create two process and I am creating a pipe for storage the information beetween iterations. In the first cycle it gives the correct value but in the second iterration it gives two errors.
My code:
def processMain():
number = 0
r, w = os.pipe()
for _ in range(2):
pid = os.fork()
if pid == 0:
number = int(number)
number += 1
number = str(number)
os.close(r)
w = os.fdopen(w, "w")
w.write(number)
print("write")
sys.exit(0)
else:
os.wait()
os.close(w)
r = os.fdopen(r)
number = r.read()
print("read")
print(number)
I excute the function and it gives me this results:
write
read
Traceback (most recent call last):
File "/home/aluno-di/area-de-aluno/SO/projeto/grupoXX/tests.py", line 31, in <module>
processMain()
File "/home/aluno-di/area-de-aluno/SO/projeto/grupoXX/tests.py", line 15, in processMain
os.close(r)
TypeError: '_io.TextIOWrapper' object cannot be interpreted as an integer
Traceback (most recent call last):
File "/home/aluno-di/area-de-aluno/SO/projeto/grupoXX/tests.py", line 31, in <module>
processMain()
File "/home/aluno-di/area-de-aluno/SO/projeto/grupoXX/tests.py", line 24, in processMain
os.close(w)
OSError: [Errno 9] Bad file descriptor
I don't understand what I am doing wrong or what I am not doing that I need to do to this work.
This should work. Note that number needs to be a shared memory value if you want the incrementing done by the child process reflected in the main process:
import os
from multiprocessing import Value, Pipe
import sys
def processMain():
number = Value('i', 0)
r, w = Pipe(duplex=False)
for _ in range(2):
pid = os.fork()
if pid == 0:
number.value += 1
n = number.value
w.send(n)
sys.exit(0)
else:
n = r.recv()
print("read", n)
os.waitid(os.P_PID, pid, os.WEXITED)
processMain()
Prints:
read 1
read 2
Re-assigning r = os.fdopen(r) is problematic here because the return value of os.fdopen is a TextIOWrapper, while the functions that use r require the value to be an integer. The first time you run the loop it works just fine because r is assigned to the first return from os.pipe(), however, then on it's converted to the TextIOWrapper where it will fail for both os.fdopen() and os.close()
Also, depending on the return value of r.read(), it's possible to get a None value, causing the program to fail when you try to run number = int(number)

EOFError: EOF when reading a line. What is this Error and why is it occuring?

I wanted to write a function that prints True if the pin the user inputted was 4 or 6 in length. I wrote the function, but when I run it outputs this error. How do I fix this error and what is wrong with it in the first place?
pin = raw_input("Please enter your four or six digit pins")
def validate_pin(pin):
if len(pen) == 4 or 6:
purp = True
else:
purp = False
return(purp)
print purp
validate_pin(pin)
Traceback (most recent call last):
File "main.py", line 1, in <module>
from solution import *
File "/home/codewarrior/solution.py", line 1, in <module>
pin = input("Please enter your four or six digit pins")
EOFError: EOF when reading a line
There are several errors in your code, however, I was unable to create your specific error message. Most likely your raw_input failed.
Here is your fixed code:
pin = raw_input("Please enter your four or six digit pins")
def validate_pin(pin):
if len(pin) in [4, 6]:
# your old code results in two boolean statements
# 1) len(pin) == 4, this correctly checks for a length of 4
# 2) or 6, this is always true, result in your if statement
# always being true
purp = True
else:
purp = False
print purp
# if your print statement comes after a return statement,
# it is never executed
return(purp)
validate_pin(pin)

How to catch and manage exceptions for GPS module?

I have a raspberry pi using a GPS module. To use the module, I am running a code such as this:
##Prints the latitude and longitude every second.
import time
import microstacknode.hardware.gps.l80gps
if __name__ == '__main__':
gps = microstacknode.hardware.gps.l80gps.L80GPS()
while True:
data = gps.get_gpgga()
List = [list(data.values())[x] for x in [7, 9, 12]]
string=str(List)
string = string[1:-1]
text_file = open("/home/pi/fyp/gps.txt","a")
text_file.write(string + "\n")
time.sleep(1)
However, every now and then it gives this error because it cannot find my location:
Traceback (most recent call last):
File "gps.py", line 8, in <module>
data = gps.get_gpgga()
File "/usr/lib/python3/dist-packages/microstacknode/hardware/gps/l80gps.py", line 119, in get_gpgga
pkt = self.get_nmea_pkt('GPGGA')
File "/usr/lib/python3/dist-packages/microstacknode/hardware/gps/l80gps.py", line 293, in get_nmea_pkt
"Timed out before valid '{}'.".format(pattern))
microstacknode.hardware.gps.l80gps.NMEAPacketNotFoundError: Timed out before valid 'GPGGA'.
It's alright to have that error. The trouble I have is that the program stops running if it occurs. Is there a way to catch that error and get the program to loop back and try again even if it encounters this error?
UPDATE
if I try Stefan_Reinhardt's method, I would get the following error instead:
Traceback (most recent call last):
File "gps.py", line 9, in <module>
data = gps.get_gpgga()
File "/usr/lib/python3/dist-packages/microstacknode/hardware/gps/l80gps.py", line 119, in get_gpgga
pkt = self.get_nmea_pkt('GPGGA')
File "/usr/lib/python3/dist-packages/microstacknode/hardware/gps/l80gps.py", line 293, in get_nmea_pkt
"Timed out before valid '{}'.".format(pattern))
microstacknode.hardware.gps.l80gps.NMEAPacketNotFoundError: Timed out before valid 'GPGGA'.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "gps.py", line 10, in <module>
except NMEAPacketNotFoundError:
NameError: name 'NMEAPacketNotFoundError' is not defined
I agree to the answer of Oisin,
but i'd suggest to put the try-except clause only arround the line where it could happen, and pass the rest of the while-loop with a continue statement so it would look like
##Prints the latitude and longitude every second.
import time
import microstacknode.hardware.gps.l80gps
if __name__ == '__main__':
gps = microstacknode.hardware.gps.l80gps.L80GPS()
while True:
try:
data = gps.get_gpgga()
except NMEAPacketNotFoundError:
continue
List = [list(data.values())[x] for x in [7, 9, 12]]
string=str(List)
string = string[1:-1]
text_file = open("/home/pi/fyp/gps.txt","a")
text_file.write(string + "\n")
time.sleep(1)
This should work but it could get stuck in an infinite recursion loop.
##Prints the latitude and longitude every second.
import time
import microstacknode.hardware.gps.l80gps
if __name__ == '__main__':
getPos()
def getPos():
try:
while True:
gps = microstacknode.hardware.gps.l80gps.L80GPS()
data = gps.get_gpgga()
List = [list(data.values())[x] for x in [7, 9, 12]]
string=str(List)
string = string[1:-1]
text_file = open("/home/pi/fyp/gps.txt","a")
text_file.write(string + "\n")
time.sleep(1)
except microstacknode.hardware.gps.l80gps.NMEAPacketNotFoundError:
getPos()

Python write file empty

I'm trying to write a script to convert an Intel HEX file to a Verilog mem format.
I can print the strings I want to save OK (eg the read & parse bit's working) but when I try to write to a file nothing ever appears :(
ihexf = open("test.hex","r")
vmemf = open("test.mem","w")
for line in ihexf:
rlen_s = line[1:3]
addr_s = line[3:7]
rtyp_s = line[7:9]
rlen = int(rlen_s, 16)
addr = int(addr_s, 16)
rtyp = int(rtyp_s, 16)
# print(rlen_s,addr_s,rtyp_s)
if rtyp == 0:
# print('#'+addr_s)
vmemf.write('#'+addr_s+'\n')
for i in range (0, rlen):
laddr = addr + i
val_s = line[9+i*2:9+i*2+2]
val = int(val_s, 16)
# print(val_s)
vmemf.write(val_s+'\n')
# print("")
else:
print("------- End Of File ------")
ihexf.close()
vmemf.close()
My test.hex looks like
:20000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000FF000000FF000000FF555540FF0A
:20000800155540FF055540FF015540FF005540FF001540FF000540FF000140FF000040FF56
:20001000000040FF000140FF000540FF001540FF005540FF015540FF055540FF155540FF4E
:00000001FF
Any clues what I'm doing wrong?
Make sure you have closed the file and very importantly that you reposition the file pointer to the start of the file and start reading chunks.
ihexf.seek(0,0)
OK - I worked out what was happening (I think!)
Existing code works on linux but not Windows.
On Windows I was seeing the following once the script finished:
#0000
#0008
#0010
#0018
------- End Of File ------
Traceback (most recent call last):
File "C:\Users\Nigel\SkyDrive\Files\python\intexhex2v.py", line 8, in <module>
rlen = int(rlen_s, 16)
ValueError: invalid literal for int() with base 16: ''`
Looks like things were messing up at the end of the file read.
Adding break after the End-Of-File print fixed everything
Thanks

Categories

Resources