python argparser, argument executing function - python

I was wondering how coul i execute a function in python with just a call of an argument when running that command, for example,
parser = argparse.ArgumentParser(description="Database accounts manager")
parser.add_argument("-s", "--show", help="Shows all database rows and columns", dest="show",required=False)
args = parser.parse_args()
if args.show:
print("i am beautiful")
what i would like is to when i call this file : python file.py -s or python file.py --show, i would like it to execute a function like i wrote for an example : "print("i am beautiful")
because when i do that i need to give an argument so it executes the function: "print(...)"

Add action to the parameters:
parser.add_argument("-s", "--show", help="Shows all database rows and columns", dest="show",required=False, action="store_true")

Related

How to supply args from the argparse to an external program call via subprocess

In a task, I need to call an external program that run on terminal via python. This external program has lots of positional and optional arguments.
Here is the sample code developed sofar:
def multi_character_parameter():
parser = argparse.ArgumentParser()
parser.add_argument('b',
help="Execute tests with browser 'firefox' or 'chrome', or 'ALL")
parser.add_argument('C', help="Execute tests in cloud 'aws' or 'azure'")
parser.add_argument(
'c', help="Clear output and temp directory before executing tests")
parser.add_argument('d', help="Check syntax for test data")
parser.add_argument("--upper-case", default=False, action="store_true")
...
args = parser.parse_args()
def my_external_program():
subprocess.call(["external_program"])
Could someone please suggest:
How to supply these args to the external_program called via subprocess.
i.e. upon running say python script.py some_args, these some_args will be supplied to the external_program function for execution as external_program some_args.
What would be the better way to structure the code if the args specified in the code needs to be used at other parts of the code.
Once you set the variable args, you can access any of the arguments using dot notation.
I have edited your code to demonstrate this:
#!/usr/bin/env python3
import argparse
import subprocess
def multi_character_parameter():
parser = argparse.ArgumentParser()
parser.add_argument('--b',
help="Execute tests with browser 'firefox' or 'chrome', or 'ALL",
required=False,
default=False)
parser.add_argument('--C', help="Execute tests in cloud 'aws' or 'azure'",
required=False, default=False)
parser.add_argument(
'--c', help="Clear output and temp directory before executing tests",
required=False, default=False)
parser.add_argument('--d', help="Check syntax for test data", required=False, default=False)
parser.add_argument("--upper-case", action="store_true", required=False, default=False)
args = parser.parse_args()
return args
def my_external_program(args):
print(args)
b = str(args.b)
C = str(args.C)
c = str(args.c)
d = str(args.d)
upper_case = str(args.upper_case)
subprocess.call(["echo", b,C,c,d,upper_case ])
if __name__ == "__main__":
args = multi_character_parameter()
my_external_program(multi_character_parameter())
Now to run it chmod +x test.py
./test.py
The stdout is presented to show access to the args (the external program was subbed out for echo as the program:
Namespace(b=False, C=False, c=False, d=False, upper_case=False)
False False False False False
If you just want to literally pass all the arguments:
import sys
subprocess.call(["external_program"] + sys.argv[1:])
This takes all the arguments passed to the script (except the first, which is the script's name) and just appends them to the argument you already provided, the name of the external program - and probably works as expected.
So, if you were to run python your_script.py 1 2 3 4 (which matches your specified argument requirements), it would call external_program 1 2 3 4.
The more general answer is that you should just provide a list of arguments to subprocess.call, as described in the documentation for subprocess.call - "args should be a sequence of program arguments or else a single string or path-like object."
Since you provide no information on exactly what mapping you're after, or how the arguments to your script translate to arguments for the external program, it's not possible to be a lot more specific - other than saying you need to construct a sequence of arguments to pass to the call.
If you want to limit or restrict the arguments passed to external_program you can do something like this
allowed_args = ['--upper-case', 'b', 'c', 'C', 'd']
subprocess.run(['external_program'] + list(set(sys.argv).intersection(allowed_args)))

Passing command line arguments to Python function in script

I have a function which requires command line arguments (with optparse), which looks something like this:
def foo():
parser = optparse.OptionParser()
parser.add_option("-i", dest="input")
parser.add_option("-o", dest="output")
(options, args) = parser.parse_args()
do_something(options.input, options.output)
return
I need to call this function from another Python script.
Does anyone know how to pass arguments to this without making use of os.system('foo -i input_path -o output_path')?
Is it possible to change your structure to incorporate function arguments? If you are calling it from another script it would make it easier.
def foo(input, output):
parser = optparse.OptionParser()
parser.add_option("-i", dest="input")
parser.add_option("-o", dest="output")
(options, args) = parser.parse_args()
if options.input:
input=options.input
if options.output:
output=options.output
do_something(input, output)
return
Otherwise you can try subprocess when calling from the other script, as that allows you to use args

Allow unknown arguments using argparse

I have a python script that requires the user to enter two arguments to run it, the arguments could be named anything.
I have also used argparse to allow the users to use a switch '-h' to get instructions of what is required to run the script.
The problem is that now I have used argparse I am getting an error when I pass my two randomly named arguments with the script.
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.parse_args()
currently when I run python test.py arg1 arg2 the error is
error: unrecognized arguments: arg1 arg2
I would like the code to allow the user to run test.py with a -h if required to see the instructions but also allow them to run the script with any two arguments as well.
Resolution with help tag to provide the user with context regarding the arguments required.
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help', help='To run this script please provide two arguments: first argument should be your scorm package name, second argument should be your html file name. Note: Any current zipped folder in the run directory with the same scorm package name will be overwritten.')
parser.add_argument('package_name', action="store", help='Please provide your scorm package name as the first argument')
parser.add_argument('html_file_name', action="store", help='Please provide your html file name as the second argument')
parser.parse_args()
Try the following code :-
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.add_argument('arg1')
parser.add_argument('arg2')
args, unknown = parser.parse_known_args()
All your unknown arguments will be parsed in unknown and all known in args.
import argparse
parser = argparse.ArgumentParser(description='sample')
# Add mandatory arguments
parser.add_argument('arg1', action="store")
parser.add_argument('arg2', action="store")
# Parse the arguments
args = parser.parse_args()
# sample usage of args
print (float(args.arg1) + float(args.arg2))
You need to add those arguments to the parser:
parser.add_argument("--arg1", "-a1", dest='arg1', type=str)
parser.add_argument("--arg2","-a2", dest='arg2', type=str)
If those arguments don't have the param required=true, you will be able to call the program without this arguments, so you can run the program with only the -h flag. To run the program with the arguments:
python test.py --arg1 "Argument" --arg2 "Argument"
Then, to have the arguments in variables you have to read them:
args = parser.parse_args()
argument1=args.arg1
argument2=args.arg2

Python error: the following arguments are required

I have the Python script that works well when executing it via command line.
What I'm trying to do is to import this script to another python file and run it from there.
The problem is that the initial script requires arguments. They are defined as follows:
#file one.py
def main(*args):
import argparse
parser = argparse.ArgumentParser(description='MyApp')
parser.add_argument('-o','--output',dest='output', help='Output file image', default='output.png')
parser.add_argument('files', metavar='IMAGE', nargs='+', help='Input image file(s)')
a = parser.parse_args()
I imported this script to another file and passed arguments:
#file two.py
import one
one.main('-o file.png', 'image1.png', 'image2.png')
But although I defined input images as arguments, I still got the following error:
usage: two.py [-h] [-o OUTPUT]
IMAGE [IMAGE ...]
two.py: error: the following arguments are required: IMAGE
When calling argparse with arguments not from sys.argv you've got to call it with
parser.parse_args(args)
instead of just
parser.parse_args()
If your MAIN isn't a def / function you can simulate the args being passed in:
if __name__=='__main__':
# Set up command-line arguments
parser = ArgumentParser(description="Simple employee shift roster generator.")
parser.add_argument("constraints_file", type=FileType('r'),
help="Configuration file containing staff constraints.")
parser.add_argument("first_day", type=str,
help="Date of first day of roster (dd/mm/yy)")
parser.add_argument("last_day", type=str,
help="Date of last day of roster (dd/mm/yy)")
#Simulate the args to be expected... <--- SEE HERE!!!
argv = ["",".\constraints.txt", "1/5/13", "1/6/13"]
# Parse arguments
args = parser.parse_args(argv[1:])

Creating artificially parsed arguments

My program "program.py" has the form:
if __name__=='__main__':
args = parse_args()
main_function(args)
However, if I import program.py as a module and run program.main_function, how can I pass the parsed arguments structure as an argument to the main_function?
Here is the definition of the parse_args()
def parse_args():
parser=argparse.ArgumentParser()
parser.add_argument(...)
args=parser.parse_args()
return args
If we are talking about argparse.parse_args from the standard library, just pass the list of arguments explicitly.
For example, if you call your program from the command line with these arguments:
program --verbose --mode=3 file1 file2
the shell splits the command line into five words, the program name and its four arguments. These are stored in sys.argv.
To achieve the same effect directly from Python:
args = parse_args(['--verbose', '--mode=3', 'file1' , 'file2'])
main_function(args)
UPDATE - parse_args modification:
def parse_args(arglist=None):
parser=argparse.ArgumentParser()
parser.add_argument(...)
args=parser.parse_args(arglist)
return args

Categories

Resources