Try and except exit error after executing the except line - try-catch

I am trying to exit out of the program after executing the except line. I have tried sys.exit(1) but it is not working. I am opening an .txt file and and passing it through the code. The code works perfectly. I am just trying to exit out of the code if the wrong file is input like temp file rather then temp.txt.
# Ask input from the user
fname = input("Enter File Name: ")
# Open the file and check if entry is valid
try:
temp_file = open(fname)
except:
print("File cannot be opened:", fname)
# I NEED YOUR HELP HERE
quit()
count = 0
total = 0
for temp in temp_file:
# Remove white space
temp = temp.strip()
# Find the exact string
if temp.startswith("X-DSPAM-Confidence:"):
# Find the position of the number and convert to float
pos = temp.find(":")
float_pos = float(temp[pos+1:])
# Add the numbers and count the number of lines
total += float_pos
count += 1
# Print out the average
print("Average spam confidence: ", total/count)

Related

How to use a While Loop to repeat the code based on the input variable

i'm having a rough time trying to do a loop with the while function.
Basicly i want the code to show me all prime numbers from 0 to the number i wrote in input.
Then, to ask a question if i want to do it one more time (if yes to repeat the code from the start) or if not to exit.
How i got it now is just to repeat the last results infinitely.
All results i found online with the while loop don't really explain how to repeat a certain part of the code.
I'm by no means even a little bit educated when it comes to this stuff so if its a stupid question, please forgive me.
# Python program to print all primes smaller than or equal to
# n using Sieve of Eratosthenes
def start(welcome):
print ("welcome to my calculation.")
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p ** 2, n + 1, p):
prime[i] = False
p += 1
prime[0] = False
prime[1] = False
print("Primary numbers are:")
for p in range(n + 1):
if prime[p]: print(p)
# driver program
if __name__ == '__main__':
n = value
SieveOfEratosthenes(n)
pitanje = input("do you want to continue(yes/no)?")
while pitanje == ("yes"):
start: SieveOfEratosthenes(n)
print("continuing")
if pitanje == ("no"):
print("goodbye")
strong text
Firstly you should remove
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
from the top of your code, everything must be inside your __main__ program.
Basically what you need to do is create a main While loop where your program is gonna run, it will keeps looping until the response is not "yes".
For each iteration, you ask a new number at the beggining and if it has to keep looping at the end.
Something like this:
# driver program
if __name__ == '__main__':
# starts as "yes" for first iteration
pitanje = "yes"
while pitanje == "yes":
# asks number
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
# show results
start: SieveOfEratosthenes(value)
# asks for restart
pitanje = input("do you want to continue(yes/no)?")
#if it's in here the response wasn't "yes"
print("goodbye")

Adding numbers to each line in a file in haxe language

Need some help, writing a program that will read the text from a file, but will
put at the beginning of each line a number, in such a way that each line is numbered in ascending order
example:
file1
a
b
c
What I want to see:
1: a
2: b
3: c
Process:
Read contents of file into a String
Split by line ending into Array<String>
Iterate and mutate contents line by line
Join by line ending back into a String
Write back into file
Sample code for any sys target:
var arr = sys.File.getContent('file.txt').split("\n");
for(i in 0...arr.length) {
arr[i] = (i+1) + ": " + arr[i];
}
sys.File.saveContent('file.txt', arr.join("\n"));

awk array that overtypes itself when printed

this is my first question so please let me know if I miss anything.
This is an awk script that uses arrays to make key-value pairs.
I have a file that has a header information separated by colons. The data is below it and separated by colons as well. My goal is to make key-value pairs that print out to a new file. I have everything set to be placed in arrays and it prints out almost perfectly.
Here is the input:
...:iscsi_name:iscsi_alias:panel_name:enclosure_id:canister_id:enclosure_serial_number
...:iqn.1111-00.com.abc:2222.blah01.blah01node00::11BLAH00:::
Here is the code:
#!/bin/awk -f
BEGIN {
FS = ":"
}
{
x = 1
if (NR==1) {
num_fields = NF ###This is done incase there are uneven head fields to data fields###
while (x <= num_fields) {
head[x] = $x
x++
}
}
y = 2
while (y <= NR) {
if (NR==y) {
x = 1
while (x <= num_fields) {
data[x] = $x
x++
}
x = 1
while (x <= num_fields) {
print head[x]"="data[x]
x++
}
}
y++
}
}
END {
print "This is the end of the arrays and the beginning of the test"
print head[16]
print "I am head[16]-"head[16]"- and now I'm going to overwrite everything"
print "I am data[16]-"data[16]"- and I will not overwrite everything, also there isn't any data in data[16]"
}
Here is the output:
...
iscsi_name=iqn.1111-00.com.abc
iscsi_alias=2222.blah01.blah01node00
panel_name=
enclosure_id=11BLAH00
canister_id=
=nclosure_serial_number ### Here is my issue ###
This is the end of the arrays and the beginning of the test
enclosure_serial_number
- and now I'm going to overwrite everything
I am data[16]-- and I will not overwrite everything, also there isn't any data in data[16]
NOTE: data[16] is not at the end of a line, for some reason, there is an extra colon on the data lines, hence the num_fields note above
Why does head[16] overwrite itself? Is it that there is a newline (\n) at the end of the field? If so, how do I get rid of it? I have tried adding subtracting the last character, no luck. I have tried to limit the number of characters the array can take in on that field, no luck. I have tried many more ideas, no luck.
Full Disclosure: I am relatively new to all of this, I might have messed up these previous fixes!
Does anyone have any ideas as to why this is happening?
Thanks!
-cheezter88
your script is unnecessarily complex. If you want to adjust the record size with the first row, do it so.
(I replaced "..." prefix with "x")
awk -F: 'NR==1 {n=split($0,h); next} # populate header fields and record size
NR==2 {for(i=1;i<=n;i++) # do the assignment up to header size
print h[i]"="$i}' file
x=x
iscsi_name=iqn.1111-00.com.abc
iscsi_alias=2222.blah01.blah01node00
panel_name=
enclosure_id=11BLAH00
canister_id=
enclosure_serial_number=
if you want to do this for the rest of the records, remove the NR==2 condition,

PYTHON- Print Certain Number of Lines in File?

I want my program to read a number of lines determined by the user, but I only know how to make it print a certain number of bytes (stored in fLine). Can someone help me out? Thank you!!
fName = raw_input("hello what file would you like to open?: ")
fLine = int(raw_input("how many lines would you like to print?: "))
try:
inFile = open(fName, 'r')
except:
print "failed to open %s sry" % fName
else:
line = inFile.read(fLine)
print line
inFile.close()
You want to use Python? If yes, try to use readlines() function .

Ways to validate converted code from FORTRAN to C

I have converted around 90+ fortran files into C files using a tool and I need to validate that the conversion is good or not.
Can you give me some ideas on how best to ensure that the functionality has been preserved through the translation?
You need verification tests that exercise those fortran functions. Then you run those tests against the c code.
You can use unit test technology/methodology. In fact I can't see how else you would prove that the conversion is correct.
In lots of unit test methodologies you would write the tests in the same language as the code, but in this case I recommend very very strongly to pick one language and one code base to exercise both sets of functions. Also don't worry about be trying to create pure unit tests rather use the techniques to give you coverage of all the use that the fortran code was supposed to handle.
Use unit tests.
First write your unit tests on the Fortran code and check whether they all run correctly, then rewrite them in C and run those.
The problem in this approach is that you also need to rewrite your unit test, which you normally don't do when refactoring code (except for API changes). This means that you might end up debugging your ported unit testing code as well, beside the actual code.
Therefore, it might be better to write testing code that contains minimal logic and only write the results of the functions to a file. Then you can rewrite this minimal testing code in C, generate the same files and compare the files.
Here is what I did for a "similar" task (comparing fortran 90 to fortran 90 + OpenACC GPU accelerated code):
Analyze what's the output of each Fortran module.
Write these output arrays to .dat files.
Copy the .dat files into a reference folder.
Write the output of the converted modules to files (either CSV or binary). Use the same filename for convenience.
Make a python script that compares the two versions.
I used convenience functions like these in fortran (analogous for 1D, 2D case):
subroutine write3DToFile(path, array, n1, n2, n3)
use pp_vardef
use pp_service, only: find_new_mt
implicit none
!input arguments
real(kind = r_size), intent(in) :: array(n1,n2,n3)
character(len=*), intent(in) :: path
integer(4) :: n1
integer(4) :: n2
integer(4) :: n3
!temporary
integer(4) :: imt
call find_new_mt(imt)
open(imt, file = path, form = 'unformatted', status = 'replace')
write(imt) array
close(imt)
end subroutine write3DToFile
In python I used the following script for reading binary Fortran data and comparing it. Note: Since you want to convert to C you would have to adapt it such that you can read the data produced by C instead of Fortran.
from optparse import OptionParser
import struct
import sys
import math
def unpackNextRecord(file, readEndianFormat, numOfBytesPerValue):
header = file.read(4)
if (len(header) != 4):
#we have reached the end of the file
return None
headerFormat = '%si' %(readEndianFormat)
headerUnpacked = struct.unpack(headerFormat, header)
recordByteLength = headerUnpacked[0]
if (recordByteLength % numOfBytesPerValue != 0):
raise Exception, "Odd record length."
return None
recordLength = recordByteLength / numOfBytesPerValue
data = file.read(recordByteLength)
if (len(data) != recordByteLength):
raise Exception, "Could not read %i bytes as expected. Only %i bytes read." %(recordByteLength, len(data))
return None
trailer = file.read(4)
if (len(trailer) != 4):
raise Exception, "Could not read trailer."
return None
trailerUnpacked = struct.unpack(headerFormat, trailer)
redundantRecordLength = trailerUnpacked[0]
if (recordByteLength != redundantRecordLength):
raise Exception, "Header and trailer do not match."
return None
dataFormat = '%s%i%s' %(readEndianFormat, recordLength, typeSpecifier)
return struct.unpack(dataFormat, data)
def rootMeanSquareDeviation(tup, tupRef):
err = 0.0
i = 0
for val in tup:
err = err + (val - tupRef[i])**2
i = i + 1
return math.sqrt(err)
##################### MAIN ##############################
#get all program arguments
parser = OptionParser()
parser.add_option("-f", "--file", dest="inFile",
help="read from FILE", metavar="FILE", default="in.dat")
parser.add_option("--reference", dest="refFile",
help="reference FILE", metavar="FILE", default="ref.dat")
parser.add_option("-b", "--bytesPerValue", dest="bytes", default="4")
parser.add_option("-r", "--readEndian", dest="readEndian", default="big")
parser.add_option("-v", action="store_true", dest="verbose")
(options, args) = parser.parse_args()
numOfBytesPerValue = int(options.bytes)
if (numOfBytesPerValue != 4 and numOfBytesPerValue != 8):
print "Unsupported number of bytes per value specified."
sys.exit()
typeSpecifier = 'f'
if (numOfBytesPerValue == 8):
typeSpecifier = 'd'
readEndianFormat = '>'
if (options.readEndian == "little"):
readEndianFormat = '<'
inFile = None
refFile = None
try:
#prepare files
inFile = open(str(options.inFile),'r')
refFile = open(str(options.refFile),'r')
i = 0
while True:
passedStr = "pass"
i = i + 1
unpackedRef = None
try:
unpackedRef = unpackNextRecord(refFile, readEndianFormat, numOfBytesPerValue)
except(Exception), e:
print "Error reading record %i from %s: %s" %(i, str(options.refFile), e)
sys.exit()
if (unpackedRef == None):
break;
unpacked = None
try:
unpacked = unpackNextRecord(inFile, readEndianFormat, numOfBytesPerValue)
except(Exception), e:
print "Error reading record %i from %s: %s" %(i, str(options.inFile), e)
sys.exit()
if (unpacked == None):
print "Error in %s: Record expected, could not load record it" %(str(options.inFile))
sys.exit()
if (len(unpacked) != len(unpackedRef)):
print "Error in %s: Record %i does not have same length as reference" %(str(options.inFile), i)
sys.exit()
#analyse unpacked data
err = rootMeanSquareDeviation(unpacked, unpackedRef)
if (abs(err) > 1E-08):
passedStr = "FAIL <-------"
print "%s, record %i: Mean square error: %e; %s" %(options.inFile, i, err, passedStr)
if (options.verbose):
print unpacked
except(Exception), e:
print "Error: %s" %(e)
finally:
#cleanup
if inFile != None:
inFile.close()
if refFile != None:
refFile.close()

Resources