I need to take an optional argument when running my Python script:
python3 myprogram.py afile.json
or
python3 myprogram.py
This is what I've been trying:
filename = 0
parser = argparse.ArgumentParser(description='Create Configuration')
parser.add_argument('filename', type=str,
help='optional filename')
if filename is not 0:
json_data = open(filename).read()
else:
json_data = open('defaultFile.json').read()
I was hoping to have the filename stored in my variable called "filename" if it was provided. Obviously this isn't working. Any advice?
Please read the tutorial carefully. http://docs.python.org/howto/argparse.html
i believe you need to actually parse the arguments:
parser = argparse.ArgumentParser()
args = parser.parse_args()
then filename will be come available args.filename
Check sys.argv. It gives a list with the name of the script and any command line arguments.
Example script:
import sys
print sys.argv
Calling it:
> python script.py foobar baz
['script.py', 'foobar', 'baz']
If you are looking for the first parameter sys.argv[1] does the trick. More info here.
Try argparse's default parameter, its well documented.
import argparse
parser = argparse.ArgumentParser(description='Create Configuration')
parser.add_argument('--file-name', type=str, help='optional filename',
default="defaultFile.json")
args = parser.parse_args()
print(args.file_name)
Output:
$ python open.py --file-name option1
option1
$ python open.py
defaultFile.json
Alternative library:
click library for arg parsing.
Related
I have written a code function.py in python which has input file path and a output file path and some flags . currently I have hardcoded everything.I want to use command line arguments to provide these inputs so that anyone can run my script by providing input to cmd.how can I do it in python?
In CMD
function.py "input file path" "output file path"
A very rudimentary example would be:
import sys
input_file_path = sys.argv[1]
output_file_path = sys.argv[2]
Note that sys.argv[0] would be your filename. You should also do the relevant checks to make sure there are the correct number of arguments, whether they are valid, etc.
As an alternative to sys.argv, I prefer argparse.
As an example:
# Import the argparse module
import argparse
# Define a function to use argparse to parse your command-line arguments
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-i",
"--input-file",
dest="input_file",
help="File to use as input",
type=str
)
parser.add_argument(
"-o",
"--output-file",
dest="output_file",
help="File to output to",
type=str
)
return parser.parse_args()
# If calling this module from the command line, this `if` statement will evaluate to True
if __name__ == "__main__":
# Parse your command-line arguments
args = parse_args()
# Get the parsed value of the "-i" argument:
infile = args.input_file
# Get the parsed value of the "-o" argument:
outfile = args.output_file
I'll explain the problem with an example. Suppose we have the following code for a random python program:
import argparse
parser = argparse.ArgumentParser(prog="webduino-generator",
description="Webduino source builder")
# Global arguments
parser.add_argument("-v", "--verbose",
action="store_true", dest='verbose',
help="Enable verbose output")
subparsers = parser.add_subparsers(dest="command")
parser_build = subparsers.add_parser("build", help="Build it")
parser_open = subparsers.add_parser("open", help="Open it")
# Check arguments
args = parser.parse_args()
print(args)
Now with this parser, I can do
program.py -v open
which is great! However, I cannot do
program.py open -v
Also the parent/global argument -v will not be listed on the help page of the sub parser.
Is there a way to make this work and add it to the help page of the subparser?
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
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.
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.
I'm trying to parse the command line arguments in a very simple way:
$ python main.py --path /home/me/123
or
$ python main.py --path=/home/me/123
And then:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--path')
args = parser.parse_args()
And args returns nothings:
(Pdb) args
(Pdb) args.path
How can I access the value of --path?
You can print args.path and it will show your line argument. For more details you can check the below link for more details about argparse
Argparse Tutorial
You can also use sys to parse your command line arguments, such as
>>> import sys
>>> path = sys.argv[1] # sys.argv always start at 1
>>> print path
Check the below link for more details.
Python Command Line Arguments
Hope it helps.
It works fine for me...
>>> args
Namespace(path='/home/me/123')
So you can access it via args.path
I would like to parse arguments passed from the command line with the prefix option as such :
python myApp.y -f file.xml
I am using python 2.6.6 so I cannot use argparse.
And I would like to make it a bit more generic and scalable than
arg1 = sys.argv[1]
arg2 = sys.argv[2]
And then use ifs to check the values and whether they have been provided.
You could use optparse, but argparse is available and can easily be installed on python 2.6.
Here's how you'd do it with argparse:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f','--filename',action='store',help='file!')
namespace = parser.parse_args()
print namespace.filename
Or with optparse:
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--filename", dest="filename",help="file!")
options, args = parser.parse_args()
print options.filename