Peter Hanson
Peter Hanson

Reputation: 193

Command line prompted errors

My program takes 2 or 3 command line parameters:

-s is an optional parameter, indicating a switch in my program later on -infile is the file input -outfile is to be the written file

I need my program to print an error message and quit if any of the following happen:

I have written:

def getGenes(spliced, infile, outfile):
spliced = False
if '-s' in sys.argv:
    spliced = True
    sys.argv.remove('-s')
    infile, outfile = sys.argv[1:]
if not infile.endswith('.genes'):
    print('Incorrect input file type')
    sys.exit(1)
if not outfile.endswith('.fa' or '.fasta'):
    print('Incorrect output file type')
    sys.exit(1)
if not 2 <= len(sys.argv) <= 3:
    print('Command line parameters missing')
    sys.exit(1)
if sys.argv[1] != '-s':
    print('Invalid parameter, if spliced, must be -s')
    sys.exit(1)

However, something is conflicting with some of the conditionals, including the first and last one being contradictory due to the fact that s.argv[1] always unequal to '-s' becuase if 's' were present in argv, it was removed earlier. So I am not sure how to write this correctly...

Upvotes: 1

Views: 3556

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

sliced=False is not indented

def getGenes(spliced, infile, outfile):
     spliced = False

sys.argv.remove('s') it should be sys.argv.remove('-s')

two conditions are contradicting each other:

if '-s' in sys.argv:
    spliced = True
    sys.argv.remove('-s') # you removed '-s' from sys.argv ,so the below if condition becomes false
    infile, outfile = sys.argv[1:]  

if sys.argv[1] != '-s':
    print('Invalid parameter, if spliced, must be -s')
    sys.exit(1)

Edited version of your code:

import sys

def getGenes(spliced, infile, outfile):
 spliced = False
if '-s' in sys.argv:
    spliced = True
    infile, outfile = sys.argv[2:]
if not infile.endswith('.genes'):
    print('Incorrect input file type')
    sys.exit(1)
if not outfile.endswith('.fa' or '.fasta'):
    print('Incorrect output file type')
    sys.exit(1)
if not 3 <= len(sys.argv) <= 4:
    print('Command line parameters missing')
    sys.exit(1)
if sys.argv[1] != '-s':
    print('Invalid parameter, if spliced, must be -s')
    sys.exit(1)

Upvotes: 1

Related Questions