I am trying to run a simple python document which takes --n or --name attribute to display a simple output.
My code is below
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--name", required=True,
help="name of the user")
args = vars(ap.parse_args())
print("Hi there {}, it's nice to meet you!".format(args["name"]))
When I run this python code with cmd (D:\User\Name> python filename.py --name Name) I don't get any output, while I aim to get the output Hi there Name, it's nice to meet you! What am I missing here?
Related
I am a beginner in programming, I am using the example
import argparse
import pandas as pd
def read_data(fname):
return pd.read_csv(fname)
if __name__ == "__main__":
options = argparse.ArgumentParser()
options.add_argument("-f", "--file", type=str, required=True)
args = options.parse_args()
data = read_data(args.file)
print(data)
I got this error:
error: the following arguments are required: -f/--file
Would you please help me how can define my file name, where to write it?
Thank you
With required=True, the command-line must include the -f or --file arguments:
# python myprog.py --file=somefile.txt
Make required=False
options.add_argument("-f", "--file", type=str, required=False)
Your original code would require yourprogram -f filename.csv where yourprogram is the name of your script file, and filename.csv is the name of a CSV file with input data. The -f option can also be spelled out in longhand as --file.
But options should typically be optional. Make this a regular required argument if it is mandatory.
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("file", type=str)
args = parser.parse_args()
data = read_data(args.file)
print(data)
Usage: yourprogram filename.csv
Perhaps you are using python yourprogram.py to run this script; then the usage would be python yourprogram.py filename.csv
Hi I am trying to implement a small program which takes in 1 flag -s and a file
I would like to do the following:
When I want to sort:
$./my_program.py -s someFile.txt
when I dont want to sort:
$./my_program.py someFile.txt
Here is what I tried:
import argparse
parser = argparse.ArgumentParser(description='A tutorial of argparse!')
parser.add_argument("-s", default=False, type=bool, help="Is the DAG sorted? If yes, use the \'-s\' flag")
parser.add_argument('filename', help="Your database file")
args = parser.parse_args()
When I tried to run it from commandline I tried this:
my_program.py -s SortedDB.txt
I get:
error: the following arguments are required: filename
If I do this:
my_program.py -s filename SortedDB.txt
it works
or this:
iota_ledger_task.py iotaSortedDB.txt
it goes to the non sorted case (expected behavior), works.
What may I be doing wrong here?
You need action="store_true" instead type=bool
Documentation: Actions
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
So, I'm writing a program in python using argparse. But my problem is it behaves differently in python 2 and 3. Here's the code
import argparse,sys
class CustomParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('\033[91mError: %s\n\033[0m' % message)
self.print_help()
sys.exit(2)
parser = CustomParser(description='Short sample app')
subparsers = parser.add_subparsers(title='Available sub-commands', dest="choice", help="choose from one of these")
ana = subparsers.add_parser("test",
formatter_class=argparse.RawTextHelpFormatter,
description = 'test',
help ="test")
ana.add_argument("-testf", type=int, help="a test flag", required=True)
args = parser.parse_args()
in python 2 it gives output (just by typing python file.py no -h flag)
Error: too few arguments
usage: test.py [-h] {test} ...
Short sample app
optional arguments:
-h, --help show this help message and exit
Available sub-commands:
{test} choose from one of these
test test
But, if I run the same in python 3 (python3 file.py) it gives no out put. I know if I provide the -h flag then I can see the description. But I want the help description to appear just by typing python3 file.py just like the python 2. Also note, I don't want to make the subparser required.
i have a python script name as neural_net.py . It classify the mnist dataset.
What i want to do is to run it via command line by taking input from user.
The following snippet is taking input from user
file=input()
from PIL import Image
im = Image.open(file).convert('L')
imr=np.array(im).T
single_test = imr.reshape(1,400)
plt.figure(figsize=(5,5))
plt.imshow(imr)
print("value is",nn.predict(single_test))
in command prompt i have to run it as following
python neural_net.py
execute the above line and then give the input
pic_0.png
and it return me the output.
What i want is to do the both of above things as a single command such as
python neural_net.py pic_0.png
Use in code
import sys
file = sys.argv[1]
to get it.
Now you can run it as
python neural_net.py pic_0.png
and file will be pic_0.png
If you run with more arguments
python neural_net.py pic_0.png pic_1.png pic_2.png
then you will have sys.argv[2], sys.argv[3], etc. with values pic_1.png, pic_2.png
If you need more complex soluton like
script.py --input pic_0.png --output image.png
then see module argparse
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input')
parser.add_argument('-o', '--output', default='output.png')
args = parser.parse_args()
file = args.input
output_file = args.output
EDIT:
I think I realized why you are unhappy. You need to provide a path in addition to the file name, you can either do this with args like
python run.py "c:/users/user/desktop/pictures/pngs/file.png"
and use the original answers. Or simply just put a general path in the code and use the arg for the specific file.
IMAGE_FOLDER = "c:/users/user/desktop/pictures/pngs/"
file = IMAGE_FOLDER + sys.argv[1]
Original:
This is pretty much straight from google results:
CML:
python neural_net.py pic_0.png
Code:
import sys
print sys.argv[1]
Result:
"pic_0.png"
Many thanks for Google and
https://www.pythonforbeginners.com/system/python-sys-argv