I need help with this issue, I want to take an argument from user input using argparse save it to a variable and print out the result
Example:
Message to send:
-t Greeting -m hello guys how are you
prints out:
greeting hello guys how are you
this is my code:
import argparse, shlex
parser = argparse.ArgumentParser()
parser.add_argument('-t', action='store', dest='title')
parser.add_argument('-m', action='store', dest='msg')
command = raw_input('message to send')
args = parser.parse_args(shlex.split(command))
title = args.title
msg = args.msg
print title, msg
when you enter, -t hi -m hello, it works fine but when you enter more then one word, it doesn't work. Why?
Usually, when you declare a command line switch via the add_argument method, python considers that only the next world/value should be stored inside the resulting variable. That is why the following works fine:
-t hello -m world
While the following:
-t greetings -m hello world
returns something like:
greetings hello
Using nargs, you can tell python how many values should be stored in the final variable.
For example, in your code if you declare your command line switches as:
parser.add_argument('-t', action='store', dest='title', nargs='*', type=str, required=True)
parser.add_argument('-m', action='store', dest='msg', nargs='*', type=str, required=True)
Python knows that all values following the -t switch should be stored in a list called title. The same goes for the -m switch and the msg variable.
Here I also added the type and required arguments to indicate what type of value is expected and that both switches have to be present in the command line.
Fixing your entire script so far:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-t', action='store', dest='title', nargs='*', type=str, required=True)
parser.add_argument('-m', action='store', dest='msg', nargs='*', type=str, required=True)
args = parser.parse_args()
print(" ".join(args.title), " ".join(args.msg))
All you have to do is call your script as follow:
python3 your_script.py -t greetings -m hello world
This should print:
greetings hello world
as a result.
You have 2 options here. Either quote the argument with spaces like so:
-t Hi -m "Hello word1 word2"
or
use davinellulinvega's answer. To get back the entire string with nargs='*', you'd have to:
parser.add_argument('-t', action='store', dest='title', nargs='*')
parser.add_argument('-m', action='store', dest='msg', nargs='*')
....
title = ' '.join(args.title)
msg = ' '.join(args.msg)
Related
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('p', 'projectType', type=str, help = 'c or c++ project type', choices=['c', 'c++'])
parser.add_argument('i', 'inputfile', type=pathlib.Path, help = 'the input file path')
parser.add_argument('o',"outputfile",type=pathlib.Path, help= 'the output file path')
parser.add_argument
args = parser.parse_args()
when i run this code on command prompt, and enter the inputfile first for example.. it gives me an error. does Argparse have an option like getopt (where i call something with a letter before inputting it so no mix up ex, '-i ...input...'). Here this option is just for optional arguments.
Is there a way for positional arguments to do that?
As per the argparse documentation you would define it as an "optional" argument but with the required flag set to true, e.g.:
parser.add_argument('-i', '--inputfile', required=True, type=pathlib.Path, help='the input file path')
Problem: I have a parser that has 1 required arg and a subparser that accepts 3 args of which 2 are required when that sub parser is invoked
As follows
Code:
parser.add_argument("-f", "--foo", type=str, required=True, help="foo help")
subparsers=parser.add_subparsers(help="Sub parsers")
mysubparser = subparsers.add_parser("a", help="a subparser")
mysubparser.add_argument("-b", "--bar", type=str, required=True, help="bar help")
mysubparser.add_argument("-bz", "--baz", type=str, required=True, help="baz help")
mysubparser.add_argument("-bzg", "--bazinga", action="store_true", help="bazinga help")
What I tried:
my problem is that
python myscript.py -f "hi" a -b "hi" -bz "hi" works but python myscript.py a -b "hi" -bz "hi" -f "hi" doesn't. Do required args have to be specified first? I think it looks a bit clunky the first way. is there a way this can be fixed?
I want both versions to work. Or a better alternative to doing things this way
I am using Python argparse to take in parameters through the CLI. I have tried using the following but when I don't give any one of the arguments, it gives the output as None. I want then default ones to be the ones provided in const=. Please take a look.
parser = argparse.ArgumentParser()
parser.add_argument('--input', nargs='?', const='testInput')
parser.add_argument('--target', nargs='?', const='testTarget')
parser.add_argument('--msg', nargs='?', const='helloFromTheOtherSide')
args = parser.parse_args()
print args.input
If I don't give input, it prints it as None as I said. I want it to print TestInput instead..
Use the default argument:
parser = argparse.ArgumentParser()
parser.add_argument('--input', nargs='?', default='testInput')
parser.add_argument('--target', nargs='?', default='testTarget')
parser.add_argument('--msg', nargs='?', default='helloFromTheOtherSide')
args = parser.parse_args()
print args.input
With
parser.add_argument('--input', nargs='?', default='testInput', const='aConst')
you have a 3 way choice
prog # input='testInput'
prog --input # input='aConst'
prog --input myfile # input='myfile'
If you don't need that aConst option, omit the nargs='?'. Since it is a flagged argument it is already optional. It doesn't need the `?'.
parser.add_argument('--input', default='testInput')
I'm having some issues with getting argparse to run correctly. Previously, my script would be run as follows:
script.py <input_file(s)> <output_filename>
With code that looked like this:
cell_list_input = sys.argv[1:]
cell_list_output = sys.argv[len(cell_list_input)]
cell_list_input = cell_list_input[:len(cell_list_input)-1]
However, I'd like to add some argument parsing just to make it more readable and usable. Ideally, the format would be similar with the following options:
script.py -i <input_file(s)> -o <output_filename>
script.py --input_list <input_file(s)> --output <output_filename>
The argparse equivalent I'm trying to implement looks like this right now:
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_list', action='append', dest='input_list', default=[], help='Input list of cell names')
parser.add_argument('-o', '--output', action='store', dest='output', help='Output file destination/name')
cli = parser.parse_args()
I know I'm doing something wrong, but can't seem to figure out what. Any help is appreciated. Thanks!
You need to specify nargs for your input file list. Try this:
parser.add_argument('-i', '--input_list', nargs="+", action='append', dest='input_list', default=[], help='Input list of cell names')
Complete example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_list', nargs="+", default=[], help='Input list of cell names')
parser.add_argument('-o', '--output', help='Output file destination/name')
cli = parser.parse_args()
print cli
Result:
$ python i.py -i a
Namespace(input_list=['a'], output=None)
$ python i.py -i a b c -o d
Namespace(input_list=['a', 'b', 'c'], output='d')
write a script that takes two optional boolean arguments,"--verbose‚" and ‚"--live", and two required string arguments, "base"and "pattern". Please set up the command line processing using argparse.
This is the code I have so far for the question, I know I am getting close but something is not quite right. Any help is much appreciated.Thanks for all the quick useful feedback.
def main():
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('base', type=str)
parser.add_arguemnt('--verbose', action='store_true')
parser.add_argument('pattern', type=str)
parser.add_arguemnt('--live', action='store_true')
args = parser.parse_args()
print(args.base(args.pattern))
The string arguments are not required by default, so you need to state that. Also the print statement that uses the arguments is incorrect.
#!/usr/bin/python
import argparse
if __name__=="__main__":
parser = argparse.ArgumentParser(description='eg $python myargs.py --base arg1 --pattern arg2 [--verbose] [--live]')
parser.add_argument('--base', required=True, type=str)
parser.add_argument('--pattern', required=True, type=str)
parser.add_argument('--verbose', action='store_true')
parser.add_argument('--live', action='store_true')
args = parser.parse_args()
print "args.base=" + str(args.base)
print "args.pattern=" + str(args.pattern)
print "args.verbose=" + str(args.verbose)
print "args.live=" + str(args.live)
the #!/usr/bin/python at the top enables the script to be called directly, though python must be located there (to confirm, type $which python), and you must set the file to have execute permission ($chmod +x myargs.py)