Confused how to use argparse - python

I am trying to write a python script that can be run from the command line with
python script.py --input file.txt
or
python script.py -i file.txt
script.py will take in the file file.txt and open/read.
This is what I have so far:
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser(description="I'm not sure what I should write here.")
parser.add_argument('-i','--input', help='Input file name',required=True)
args = parser.parse_args()
Now...How do I actually access the input file?
What I want is to write to an output file, e.g. python script.py --outputfile file.csv? I do not understand how to interact with writing the file. Sorry if this is too easy.

It is pretty simple!
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser(description="Something like -- File reader: reads file line by line.")
parser.add_argument('-i','--input', help='Input file name',required=True)
args = parser.parse_args()
with open(args.input) as fp:
for line in fp:
print line
If you want to write some content to the input file. Open the file in write mode and write to it whatever you want.
with open(args.input, 'w') as fp:
fp.write("Hello World!")
If you want a separate file to write, add an argument to your argparser in write mode and then write to it.
parser = argparse.ArgumentParser(description="Something like -- File reader/writer: reads/writes files line by line.")
parser.add_argument('-i','--input', help='Input file name',required=True)
parser.add_argument('-o','--output', help='Output file name',type=argparse.FileType('w'),required=True)
args = parser.parse_args()
with open(args.input) as fp:
for line in fp:
print line
with open(args.output) as fp:
fp.write("Hello World!")

You can access the string the user enter after -i with:
args.input
For example:
argp_test.py -i my_file_name.txt
Now:
print(args.input)
prints:
my_file_name.txt
Next step is to read the file content:
with open(args.input) as fobj:
for line in fobj:
# do something with this line
BTW, you got a syntax error in this line:
parser = argparse.ArgumentParser(description='I'm not sure what I should write here.')
It should look like this:
parser = argparse.ArgumentParser(description="I'm not sure what I should write here.")
When you use a ' in your string, you need to use " at the begging and end of your string. So use:
"I'm not"
instead of:
'I'm not'

Related

Script called from another script with arguments from another variable

I have created the Python script below which i would like to run and call another script from and then give the called script a variable in this case it would be an email address as "line" from a text file. What would be the easiest way to accomplish this please?
The problem now is that the script that is being called will not take the 'line' variable as an argument.
import bob
import os
# file handle fh fh = open('mailout.txt') while True:
# read line
line = fh.readline()
line = line.replace("\r", "").replace("\n", "")
command = 'python3 bob.py ' + line
os.system(command)
# check if line is not a empty value
if not line:
break fh.close()
As #Zach's comment, you can call it by giving line as argument. Otherwise, you can do it by using argparse. Assume that you have two functions inner.py and outer.py.
inner.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--sentence')
args = parser.parse_args()
print(args.sentence)
outer.py
import os
f = open('email.txt')
line = f.readline()
line = line.replace("\r", "").replace("\n", "")
line = "\""+line+"\""
command = 'python inner.py -s' + line
os.system(command)
Then calling python outer.py returns
Just a line to try

How use input and output file in Python

I have a Python script that inputs all words from a file and sorts them in order:
with open(raw_input("Enter a file name: ")) as f :
for t in sorted(i for line in f for i in line.split()):
print t
But instead of asking every time for the input file I would like to choose the input file with a "-i" and save the output file with a "-o", this way:
python myscript.py -i input_file.txt -o output_file.txt
and BTW, how to save the output on a target file?
This should do it:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='infile',
help="input file", metavar='INPUT_FILE')
parser.add_argument('-o', dest='outfile',
help='output file', metavar='OUTPUT_FILE')
args = parser.parse_args()
with open(args.infile, 'r') as infile:
indata = infile.read()
words = indata.split()
words.sort()
with open(args.outfile, 'w') as outfile:
for word in words:
outfile.write('{}\n'.format(word))
argparse is a built-in module for parsing command-line options. It does all the work for you.
$ ./SO_32030424.py --help
usage: SO_32030424.py [-h] [-i INPUT_FILE] [-o OUTPUT_FILE]
optional arguments:
-h, --help show this help message and exit
-i INPUT_FILE input file
-o OUTPUT_FILE output file
To get started on your parameters, take a look at sys.argv.
To write into an output file, use the write mode "w", and .write() to it.
For the latter there are definitely good tutorials out there.

PYTHON3 error:unrecognized arguments

I'm trying to give a TXT file with argparse and then to open it in a function.
Can you tell me why it say : error:unrecognized arguments : dataBase.txt
(ps: dataBase is the file I'm trying to open)
update(1)
my main :
if __name__ =='__main__':
parser=argparse.ArgumentParser()
parser.add_argument("file_name",type= argparse.FileType,help="name of file with network")
args=parser.parse_args()
z=args.file_name
names,network= loadNetwork()
a little part of my function:
def loadNetwork():
fileName=open('z', 'r')
name = fileName.readlines()
I think it's because file is not a valid type for argparse in Python3. The type argument takes a callable, and since file doesn't exist in Python3, it'll throw an error. Try using FileType instead.
parser = argparse.ArgumentParser()
parser.add_argument("file_name", type=argparse.FileType("r"), help="name of file with network")
Here's roughly, how I think your code should look:
def loadNetwork(afile):
name = afile.readlines()
return name
if __name__ =='__main__':
parser=argparse.ArgumentParser()
parser.add_argument("file",type= argparse.FileType('r'),
help="name of file with network")
# FileType opens the file you specified;
# so you don't need to open it
args = parser.parse_args()
names,network = loadNetwork(args.file)
args.file.close()
It's a good idea to pass values set by argparse to your functions as parameters, rather than setting global variables.
But if instead you would prefer to open and close the file yourself, I'd suggest:
def loadNetwork(filename):
with open(filename) as f:
name = f.readlines()
return name
if __name__ =='__main__':
parser=argparse.ArgumentParser()
parser.add_argument("filename", help="name of file with network")
args = parser.parse_args()
names,network = loadNetwork(args.filename)
the with statement opens and closes the file. A down side to this is that argparse isn't going to issue an error message if the filename isn't valid. But the with open will. Also this doesn't accept '-' as a filename (FileType takes that to mean sys.stdin).

how to integrate optparse options with the variables names in python

I am very newbie to python and to optparse module in general. I have figured out how to add options in python script using optparse but having trouble linking the options with my variable names in python.
import sys
from optparse import OptionParser
def main ():
parser = OptionParser()
parser.add_option("-f", "--file", dest="in_filename",
help="Input fasta file", metavar="FILE")
parser.add_option("-o", "--out", dest="out_filename",
help="Output fasta file", metavar="FILE")
parser.add_option("-i", "--id", dest="id",
help="Id name to change", metavar="ID")
(options,args) = parser.parse_args()
with open(f, 'r') as fh_in:
with open(o, 'w') as fh_out:
id = i
result = {}
count = 1
for line in fh_in:
line = line.strip()
if line.startswith(">"):
line = line[1:]
result[line] = id + str(count)
count = count + 1
header = ">" + str(result[line])
fh_out.write(header)
fh_out.write("\n")
else:
fh_out.write(line)
fh_out.write("\n")
main()
When i run this i get this below traceback and error:
python header_change.py -f consensus_seq.txt -o consensus_seq_out.fa -i "my_test"
Traceback (most recent call last):
File "/Users/upendrakumardevisetty/Documents/git_repos/scripts/header_change.py", line 36, in <module>
main()
File "/Users/upendrakumardevisetty/Documents/git_repos/scripts/header_change.py", line 18, in main
with open(f, 'r') as fh_in:
NameError: global name 'f' is not defined
Can someone point to me what i am doing wrong.
You've got two problems here.
First, as the optparse tutorial shows, optparse doesn't create global variables, it creates attributes in the options namespace that it returns:
parse_args() returns two values:
options, an object containing values for all of your options—e.g. if --file takes a single string argument, then options.file will be the filename supplied by the user, or None if the user did not supply that option
args, the list of positional arguments leftover after parsing options
So, if the user typed -f, you're not going to have f, you're going to have options.f.
Second, f isn't the right name anyway. You explicitly specified a different destination, instead of the default:
parser.add_option("-f", "--file", dest="in_filename",
help="Input fasta file", metavar="FILE")
So it's going to do what you asked and store the file in in_filename.
And likewise for the other options. So, your code should start off like this:
with open(options.in_filename, 'r') as fh_in:
with open(options.out_filename, 'w') as fh_out:

String representation of file name

I have a script that uses argparse to handle command line arguments. One argument can be stdin or a file name. The basic code looks like this:
import argparse
p = argparse.ArgumentParser()
p.add_argument('--input', type=argparse.FileType('r'), default='-')
args = p.parse_args()
for line in args.input:
print line
In another section of code, I need a string representation of this file name. How can I get a string of this file name. I was trying something like this, without success:
str(args.input)
repr(args.input)
Use the .name attribute of the file object:
args.input.name
This is the filename of the open fileobject, or <stdin> for sys.stdin.

Categories

Resources