How to call external input and output file names to run Python Programs at Linux Command Prompt

2k Views Asked by At

In my Python Program, I have lines to open an input file:

f = open('/home/han/fasta.txt',"r")

and to write an output file:

with open("output.txt", "w") as text_file:
    text_file.write ("{:<16}{:<16}{:<16}{:<16}{:<16}".format('','A','C','G','T')+'\n')

However, every time I want to run the Python program in Linux Command Prompt with different, I have to change the input and output file names in codes. I would like to know how to achieve running the program at Linux command prompt exactly as below: (in which I need to enter "-i" and "-o" for input and output file names respectively)

$ python codon.py -i fasta.txt -o output.txt

I have tried for the input file name

from sys import argv
script, filename = argv
f = open(filename,"r")

but I felt it doesn't necessarily need the "-i" in command prompt.

Sorry if the question is incredibly obvious...I am new to Python

2

There are 2 best solutions below

1
On BEST ANSWER

Use python standard argparse library

import argparse

parser = argparse.ArgumentParser(description='My app description')
parser.add_argument('-i', '--input', help='Path to input file')
parser.add_argument('-o', '--output', help='Path to output file')
args = parser.parse_args()

f = open(args.input,"r")

....etc

0
On

If you don't want to use the -i, which isn't strictly obligatory, you can do as follows:

python codon.py fasta.txt output.txt

And you can get the names by using argv[1] and argv[2]:

from sys import argv
inputfile = argv[1]
outputfile = argv[2]
f = open(inputfile ,"r")
...