why my argparse program do not continue to do the next lines? - python

BSD
hi guys, i wrote a program that takes arguments with argparse and the stores it in variables,
then the variables contents is used to be passed out to an XML file that i want to create;
gere is a snippet from my code:
import argparse
from lxml import etree
if __name__ == '__main__':
my_parser = argparse.ArgumentParser()
my_parser.add_argument('U', type=str, action='store', help='Enter the account user name')
my_parser.add_argument('P', type=str, action='store', help='Enter the account password')
my_parser.add_argument('i', type=str, action='store', help='Enter the phone Number To Send
the SMS')
my_parser.add_argument('k', type=str, action='store', help='Enter the senders phone
number')
my_parser.add_argument('data', type=str, action='store', help='Enter the text for SMS')
my_parser.add_argument('e', type=str, action='store', help='send sms?')
args = my_parser.parse_args()
username = args.U
password = args.P
phone = args.i
reply = args.k
data = args.data
#print(args.U, args.P, args.i, args.k, args.data)
if args.e:
# Create the root element
page = etree.Element('sms')
# Make a new document tree
doc = etree.ElementTree(page)
# Add the subelements
pageElement1 = etree.SubElement(page, 'Account')
subelement2 = etree.SubElement(pageElement1, 'id').text = username
subelement3 = etree.SubElement(pageElement1, 'password').text = password
# Add the subelements for "Attributes" tree
pageElement2 = etree.SubElement(page, 'Attributes')
subelement4 = etree.SubElement(pageElement2, 'reference').text = '123'
subelement5 = etree.SubElement(pageElement2, 'replyPath').text = reply
# Save to XML file
doc.write('output.xml', xml_declaration=True, encoding='utf-8')
when i run it from the CMD, it runs only the first part, but the XML part is not executed.
can someone plz help?
thanks

The issue according to me is when you are running the command you are not sending value from command prompt for e. Try using following command:-
python your_filename.py e="your value"
or you can also use following command:-
python your_filename.py --e "your value"
And print out the value of args.e

Related

python argparse default with nargs wont work [duplicate]

This question already has answers here:
Argparse optional argument with different default if specified without a value
(2 answers)
Closed last month.
Here is my code:
from argparse import ArgumentParser, RawTextHelpFormatter
example_text = "test"
parser = ArgumentParser(description='my script.',
epilog=example_text,
formatter_class=RawTextHelpFormatter)
parser.add_argument('host', type=str, default="10.10.10.10",
help="Device IP address or Hostname.")
parser.add_argument('-j','--json_output', type=str, default="s", nargs='?',choices=["s", "l"],
help="Print GET statement in json form.")
#mutally exclusive required settings supplying the key
settingsgroup = parser.add_mutually_exclusive_group(required=True)
settingsgroup.add_argument('-k', '--key', type=str,
help="the api-key to use. WARNING take care when using this, the key specified will be in the user's history.")
settingsgroup.add_argument('--config', type=str,
help="yaml config file. All parameters can be placed in the yaml file. Parameters provided from form command line will take priority.")
args = parser.parse_args()
print(args.json_output)
my output:
None
Everything I am reading online says this should work, but it doesn't. Why?
You could use the const= parameter. const stores its value when the option is present but have no values
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-j', '--json-output', nargs='?', choices=['s', 'l'], const='s')
args = parser.parse_args()
However design wise, it might be better to use the following:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output-type', choices=['json-s', 'json-l', 'normal'], default='normal')
args = parser.parse_args()

Store argparse input to use as variable

I am using argparse to require input from the user for a hardware id to then be called later on, I cannot work out how to get it so the user types
<command> --id <id>
Please help me see where I'm going wrong! Thanks
parser = argparse.ArgumentParser(description='Return a list of useful information after specifying a hardare/asset ID')
parser.add_argument('--id', type=str, required=True, help ='A hardware/asset id to provide information on')
args = vars(parser.parse_args())
args = parser.parse_args()
def main():
hardware_id = hardware_id_input
host = get_host_information(hardware_id)
print(host["hostname"])
print(host["hardware_id"])
Ditch the call to vars. You would have your argument stored as args.id after parsing. You would then call your main with the args.id as input.
Edit: added a code sample
def main(hw_id):
print(hw_id)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Description.')
parser.add_argument('--id', type=str, help='The hardware id.', required=True)
args = parser.parse_args()
main(args.id)

Using Argparse to create required argument with multiple options?

If I understand Argparse correctly, the positional arguments are the required arguments that the user can specify. I need to create a positional argument with argparse where the user can specify a certain type of argument that is displayed if he/she brings up the -h option. I've tried using add_argument_group but it simply only displays a header with a description of the other arguments when you bring up the -h option.
def Main():
parser = argparse.ArgumentParser(description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter)
parser.add_argument("input_directory",help = "The input directory where all of the files reside in")
sub_parser = parser.add_argument_group('File Type')
sub_parser.add_argument(".txt",help = "The input file is a .txt file")
sub_parser.add_argument(".n12",help = "The input file is a .n12 file")
sub_parser.add_argument(".csv",help = "The input file is a .csv file")
parser.parse_args()
if __name__ == "__main__":
Main()
So when I run the script, I should specify in order to run the script. If I choose either .txt, .n12, or .csv as my argument, then the script should run. However, if the I don't specify the file type from those 3 options listed, then the script wouldn't run.
Is there an argparse function that I'm missing that can specify multiple options for a positional argument?
Use the choices= parameter to force the user to choose from a restricted set of values.
import argparse
def Main():
parser = argparse.ArgumentParser()
parser.add_argument("input_directory",help = "The input directory where all of the files reside in")
parser.add_argument("file_type", help = "File Type", choices=['.txt', '.n12', '.csv'])
ns = parser.parse_args()
print(ns)
if __name__ == "__main__":
Main()
I think you're making this too complicated. If I understand your problem correctly, you want the user to enter two arguments: a directory name and a file type. You application will accept only three values for file type. How about simply doing this:
import argparse
def Main():
parser = argparse.ArgumentParser(description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter)
parser.add_argument("input_directory", help = "The input directory where all of the files reside in")
parser.add_argument("file_type", help="One of: .txt, .n12, .csv")
args = parser.parse_args()
print(args)
if __name__ == "__main__":
Main()
... and adding application logic to reject invalid values for file type.
You access the user-entered values through the object returned by parse_args().
Use option grouping feature use add_mutually_exclusive_group() instead of add_argument_group()
import argparse
def Main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("input_directory", help="The input directory where all of the files reside in")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-txt", action='store_true', help="The input file is a .txt file")
group.add_argument("-n12", action='store_true', help="The input file is a .n12 file")
group.add_argument("-csv", action='store_true', help="The input file is a .csv file")
print parser.parse_args()
if __name__ == "__main__":
Main()

python, argparse get argument from input- raw_input

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)

How to use python argparse with conditionally optional arguments?

Here is the current code.
import time
import collections
from modules import outputs
from modules import scrub
from modules import lookups
parser = argparse.ArgumentParser(description='AppMap Converter to Generate Asset Files from AppMapp Data')
parser.add_argument("operation", nargs='?', default="empty", help='The operation to perform')
parser.add_argument("input", nargs='?', default="empty", help='The input AppMapp File Path')
parser.add_argument("output", nargs='?', default="empty", help='The output Asset File Path')
args = parser.parse_args()
start = time.time()
if(args.operation == "Convert"):
input_file_path = args.input
output_file_path = args.output
#DO LOTS OF STUFF
else:
exit()
The script is called sacsproc, so I run it from the command line as follows:
./sacsproc Convert input.csv output.csv
This all works nicely, the problem is that I need more sacsproc commands which may have a totally different set of secondary parameters. i.e. one command might be:
./sacsproc Clean -rts input.csv output.csv err.csv
Thus, I am trying to determine how one defines arguments that are conditional on the first argument? In my mind, I'm thinking about the zfs command line utilities that do what I am trying to do (e.g. zpool create mirror sdb sdc vs. zpool remove sda).
use subparsers
subparsers = parser.add_subparsers(help="sub-command help")
group1 = subparsers.add_parser("something",help="do something")
group1.set_defaults(which="g1") # some default value (so you know which group was activated)
group1.add_argument("ARG",help='do something on ARG')
group2 = subparsers.add_parser("other",help="do something else")
group2.set_defaults(which="g2") # give some default value
group2.add_argument("ARG",help='do something else on ARG')
ok ...
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help="sub-command help")
g1 = subparsers.add_parser("thing1",help="bind to a port and just echo back anything it gets ... with a prompt")
g1.set_defaults(which="g1")
g1.add_argument("input",help='the input file')
g1.add_argument("output",help='the output file')
g2 = subparsers.add_parser("thing2",help="create a bridge between two ports, this is useful for generating a logfile")
g2.set_defaults(which="g2")
g2.add_argument("input",help='thie input file')
g2.add_argument("output",help='the output file')
g2.add_argument("error",help="the err file")
def print_help(args):
print "ARGS:",args
try:
parser.parse_args(args)
except:
print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"
print_help(["-h"])
print_help(["thing1","-h"])
print_help(["thing2","-h"])

Categories

Resources