Reputation: 23
I am writing an automation script in python using argparse module in which I want to use the -s as an option which takes file/file path as an argument. Can somebody help me to do this?
Example: ./argtest.py -s /home/test/hello.txt
Upvotes: 0
Views: 10329
Reputation: 2946
You can use
import argparse
parse = argparse.ArgumentParser()
parse.add_argument("-s")
args = parse.parse_args()
# print argument of -s
print('argument: ',args.s)
Suppose the above code is stored in the file example.py
$ python example.py -s /home/test/hello.txt
argument: /home/test/hello.txt
You can click here(Python3.x) or here(Python2.x) to learn more.
Upvotes: 0
Reputation: 20336
Just do this:
import argparse
parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-s", type=argparse.FileType('r'), help="Filename to be passed")
args = vars(parser.parse_args())
open_file = args.s
If you want to open the file for writing, just change r
to w
in type=argparse.FileType('r')
. You could also change it to a
, r+
, w+
, etc.
Upvotes: 2