0

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

1
  • Did you read the documentation for the module yet? It includes examples of how to do this. Where did you get stuck when you tried? Commented Mar 23, 2016 at 0:33

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I would omit the nargs=1; the default nargs value is usually better.
0

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.

2 Comments

Hi zondo, I used your code but it throws me an error like "AttributeError: 'dict' has no attribute 's'. Kindly help
@AlaguJeeva - Try use python-3.x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.