Okay, So I wanted to dynamically either take input from STDIN or from a file, depending on the options given on the command line. In the end I came up with this code:
# Process command-line options
# e.g., python3 trowley_FASTAToTab -i INFILE -o OUTFILE -s
try:
opts, args = getopt.getopt(sys.argv[1:], 'i:o:s')
except getopt.GetoptError as err:
# Redirect STDERR to STDOUT (insures screen display)
sys.stdout = sys.stderr
# Print help information
print(str(err))
# Print usage information
usage()
# Exit
sys.exit(2)
# Define our variables
inFile = "" # File to be read, if there is one
outFile = "" # Outfile to write to, if there is one
keepSeq = False # Whether or not to keep the sequence
header = "" # The header line we will mess with
sequence = "" # The sequence were messing with
# Parse command line options
for (opt, arg) in opts:
if opt == "-i":
inFile = str(arg)
elif opt == "-o":
outFile = str(arg)
elif opt == "-s":
keepSeq = True
# Lets open our outfile or put the variable to stdout
if not outFile:
outFile = sys.stdout
else:
outFile = open(outFile, 'w')
for line in sys.stdin:
# Do tons of stuff here
print(tmpHeader, file=outFile)
# Maybe some cleanup here
Which has some odd behavour. If i specify an infile, but no outfile, it will read that file, do the stuff, and then output the result to the screen (what it's supposed to do).
If I leave off both the infile and the outfile (so input would be from stdin), once i press ctrl d (end of input), it just does nothing, exits the script. Same thing when I take the input from stdin and write to a file, just wont do anything.
I ended up fixing it by using:
while (1):
line = inFile.readline()
if not line:
break
# Do all my stuff here
My question is, Why wont the for line in inFile work? I get no errors, just nothing happens. Is there some unspecified rule i'm breaking?