jeudi 9 novembre 2017

How to only execute IF statement if given an argument

I have a piece of code which when run through the terminal works fine when it is provided with all the arguments, however I would like one argument to be optional, and to only run the IF statement if this argument is provided, here is my code:

import argparse
import sys
import csv 

parser= argparse.ArgumentParser()
parser.add_argument('-r', '--range', help= 'Enter range of two m/z values in format of x,y', default= '1000,1500')
parser.add_argument('files', nargs= '*')
parser.add_argument('-a', '--amino_acid', help= 'Enter one letter code of amino acid you wish to search for (optional)')
args=parser.parse_args()


lower_upper = args.range.split(',')
filename= args.files[0]
fileopen= open(filename, 'r')
values=[]
user_mean=[]
amino_acids=[]
aa = args.amino_acid

lower_range= float(lower_upper[0])
upper_range= float(lower_upper[1])

for line in fileopen:
    data = line.split()
    protname, pep, mz, z, p, sequence = data
    mz = float(mz)
    #print(mz)
    values.append(mz)
    if mz >= lower_range and mz <= upper_range:
        print(mz)
        user_mean.append(mz)
        if aa in sequence:
            amino_acids.append(str(sequence))
mean = sum(user_mean)/len(user_mean)
print('Mean Value %6.2f' %mean)
print(args.range)

with open('pepmasses.csv', "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    for val in user_mean:
        writer.writerow([val])
print("pepmasses.csv created!")

print(amino_acids)

So I would like the "if aa in sequence" part to only execute if the -a arg is given, however when this argument isn't given it tries to run it anyway and fails. Any help is appreciated, thanks.

Aucun commentaire:

Enregistrer un commentaire