Is it possible to add '-' flag in argparse of python3? - python

Tools like dnsgen works with this both type of options:
Without any argument:
cat domains.txt | dnsgen - | someotherprogram
With argument:
dnsgen -w wordlist filename.txt
Can I make my program use - without argument i.e. dnsgen - style. Lets say my code is this and it can receive data from both stdin and wordlist
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-w', '--wordlist', help="Wordlist")
argv = parser.parse_args()
my_awesome_function(argv.wordlist)
So, my code reads only from wordlist. How can I make this both by wordlist and by stdin using - argument style?

May be not an elegant solution but, You can assign a dummy variable and make it store_true as below.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-', "--_", action='store_true')
parser.add_argument('-w', '--wordlist', help="Wordlist")
argv = parser.parse_args()
my_awesome_function(argv.wordlist)

Related

Passing arguments to a Python script

I want to pass arguments to a Python script in two ways,
python main.py --source=aws
and
python main.py source aws
This is my current code,
parser = argparse.ArgumentParser()
parser.add_argument("--s", "--source", help='Flag to choose source')
This makes the first option possible. How do I make the second option possible?
There is not a way to do that with Argparse. The only way to do that is by filtering stdin using sys.argv.
import argparse
import sys
mangle_my_args = ['s', 'source']
arguments=['--'+arg if arg in mangle_my_args else arg for arg in sys.argv[1:]]
parser = argparse.ArgumentParser()
parser.add_argument("--s", "--source", help='Flag to choose source')
print(parser.parse_args(arguments))

How to print just the content of the help string of a specific argument of ArgParse

Is there a way to access the help strings for specific arguments of the argument parser library object?
I want to print the help string content if the option was present on the command line. Not the complete help text that Argument Parser can display via ArgumentParser.print_help .
So something along those lines:
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--do_x", help='the program will do X')
if do_x:
print(parser.<WHAT DO I HAVE TO PUT HERE?>('do_x')
And this is the required behavior
$program -d
the program will do X
There is parser._option_string_actions which is mapping between option strings (-d or --do_x) and Action objects. Action.help attribute holds the help string.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--do_x", action='store_true',
help='the program will do X')
args = parser.parse_args()
if args.do_x:
print(parser._option_string_actions['--do_x'].help)
# OR print(parser._option_string_actions['-d'].help)
parser._actions is a list of the Action objects. You can also grab object when creating the parser.
a=parser.add_argument(...)
...
If args.do_x:
print a.help
Play with argparse in an interactive session. Look at a from such an assignment.

sed-style "-i[ext]" option parsing in Python

In Python, how can I (without reinventing the argparse wheel) support a command-line option syntax à la sed -i in which one option takes an optional argument if & only if there is no whitespace between the option and its argument?
Naïvely, I'd expect argparse to support this by setting nargs='?', like so:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-i', dest='backup', nargs='?', const='')
>>> parser.add_argument('arg', nargs='*')
... but it doesn't:
>>> parser.parse_args(['-i', '~'])
Namespace(backup='~', arg=[]) # wanted: Namespace(backup='', arg=['~'])
What options are available to me? I'd prefer answers that work in both Python 2.7 and Python 3.3+.
Quick and dirty workaround here.
First, manually check the sys.argv[1:] and check if the option (with nargs='?', const='') is used with no optional argument (including -o posarg case that we are trying to resolve here).
If that so, modify that in a way to prevent it from consuming the trailing positional arguments, by appending = at the end of it.
Then explicitly give the modified args to the parser.parse_args(argv) function.
Following is the example script:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='backup', nargs='?', const='')
parser.add_argument('arg', nargs='*')
print(parser.parse_args(['-i', '~'])) # gives Namespace(arg=[], backup='~')
print(parser.parse_args(['-i=', '~'])) # gives Namespace(arg=['~'], backup='')

Use argparse module in python to parse a single argument

I used the OptParse module a few years back, and it seemed so easy, but seeing the argparse module, it doesn't seem intuitive to use. Thus, I'd like some help.
I currently have (which isnt much yet):
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
I'd like to be able to issue a command like python myscript.py --char 20 . This value for char flag will always be an int.
If someone can please help, I'd greatly appreciate it! Thank you
This is how you add an argument, and retrieve it:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--char', type=int,
help='number of characters')
args = parser.parse_args()
char = args.char
You should check out the docs:
https://docs.python.org/3/library/argparse.html
And here's a tutorial:
https://docs.python.org/2/howto/argparse.html
you need to add an argument to the parser object, and optionally specify the parameter type to be int
# testargs.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--char', type=int)
args = parser.parse_args()
print(args.char)
if you execute this file with
python testargs.py --char 20
it should print 20 to the console

Python argparse conditional arguments

I am creating a program that requires conditional arguments using argparse. I would like to generate new arguments in my code depending on if a previous argument has been entered or not. Here is a basic example of how I would like my code to look
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-bowtie",action = "store_true",help="use to run bowtie")
args = parser.parse_args()
if args.bowtie:
parser.add_argument( add some new argument here )
args = parser.parse_args()
I've been doing a lot of stuff recently that's really similar to this. Look into subparsers:
parser = argparser.ArgumentParser
subparsers = parser.add_subparsers('-bowtie')
subparser = subparsers.add_parser()
subparser.add_argument('new argument')

Categories