I am completely new to Python, just started today and getting to grips with Python. Running it in Visual Studio btw.
Came across the import argParse and this is where things got a bit confusing for me.
I have some code I'm trying to get to work but it won't and I am quite clueless.
I'm getting an error on the code args = parser.parse_args() and I have no idea why either. Code is below
import math
import argparse
parser = argparse.ArgumentParser(description='calculate')
parser.add_argument('radius', type=int, help="radius plzz")
parser.add_argument('height', type=int, help="height plzz")
args = parser.parse_args()
def cylinder_volume(radius, height):
vol = (math.pi) * (radius ** 2) * height
return vol
if __name__ == '__main__':
print(cylinder_volume(args.radius, args.height))
I do have an idea of what's going on in this code but I don't know why it won't run as expected?
Maybe because I'm using Visual Studio? Maybe I need to import something else..
I have an image of the error!
args = parser.parse_args() parses the command line arguments (accessible as the sys.argv list) and makes the first argument args.radius and the second argument args.height, per the calls to the add_argument method. So all you need to do is to run the script from the command line with two integer arguments, e.g.:
script_name.py 123 456
or to test it in an IDE such as Visual Studio, you can pass a list of arguments to parse_args instead:
args = parser.parse_args(['123', '456'])
which outputs:
21673294.79680895
you can add 'dest=(str)' to send the argument as an attribute of args.
parser.add_argument(
'radius',
type=int,
help="radius plzz",
dest='radius'
)
parser.add_argument(
'height',
type=int,
help="height plzz",
dest='height'
)
Then you can call the arguments as you did in:
print(cylinder_volume(args.radius, args.height))
Related
I have a .py file following the normal code structure
def main( args ):
.......
.......
if __name__ == "__main__":
parser = argparse.ArgumentParser(description = “ forecasting example”)
parser.add_argument("--train-window", default=2160, type=int)
parser.add_argument("--test-window", default=336, type=int)
parser.add_argument("--stride", default=168, type=int)
parser.add_argument("-n", "--num-steps", default=501, type=int)
parser.add_argument("-lr", "--learning-rate", default=0.05, type=float)
parser.add_argument("--dct", action="store_true")
parser.add_argument("--num-samples", default=100, type=int)
parser.add_argument("--log-every", default=50, type=int)
parser.add_argument("--seed", default=1234567890, type=int)
args = parser.parse_args()
main(args)
I was trying to run this program in Jupyter notebook, but it will get errors such as
usage: ipykernel_launcher.py [-h] [--train-window TRAIN_WINDOW]
[--test-window TEST_WINDOW] [--stride STRIDE]
[-n NUM_STEPS] [-lr LEARNING_RATE] [--dct]
[--num-samples NUM_SAMPLES]
[--log-every LOG_EVERY] [--seed SEED]
ipykernel_launcher.py: error: unrecognized arguments: -f C:\Users\AppData\Roaming\jupyter\runtime\kernel-4c744f03-3278-4aaf-af5e-50c96e9e41cd.json
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
my question is that, what are the right approaches or the modifications I need to make if I want to run a python program, which setup input parameters using argparse type of mechanism, in Jupyter Notebook?
Your code should be indented differently so you can import it into your notebook, or into another Python script. The whole point of the if __name__ == "__main__": block is that it gets executed immediately when Python parses the file; the condition is true only when you run the file directly, not when you import it. But the block needs to be indented differently, so that it's not inside any def or class or other block structure.
The way to use this from a notebook, then, is to call main (or whichever other functions from the imported code you want to run) with your desired parameters.
In this case, main has been designed to expect an Argparse object as its argument, which is quite unfortunate. A better design would simply do the argument parsing inside main, and expose a different function or set of functions for reuse as a library.
Assuming your main function's internals look something like
def main(args):
print(
real_main(args.train_window, args.test_window,
stride=args.stride, num_steps=args.num_steps,
learning_rate=args.learning_rate,
dct=args.dct, num_samples=args.num_samples,
log_every=args.log_every, seed=args.seed))
and supposing you wanted to run the equivalent of
python thatfile.py -n 23 -lr 0.7--dct --num-samples 2300
the equivalent code in your notebook would look like
from thatfile import real_main as that_main
print(that_main(2160, 336, num_steps=23,
learning_rate=0.7, dct=True,
num_samples=2300))
where the first two values are simply copied from the argparse defaults, and I obviously had to speculate a great deal about which parameters are required and which are optional keyword parameters, and whether they are named identically to the argparse field names.
With this code, I can't seem to add "--height" as argument because Python is confused with the "-h / --help" default option. I've tried to add add_help=False when creating the object but I still get the error main.py: error: the following arguments are required: height
import argparse
parser = argparse.ArgumentParser(description='my description')
parser.add_argument('height', type=int, nargs=1)
args = parser.parse_args()
You created a positional argument. The way argparse works is that when you define an argument without any leading - or -- it will consider it positional, so you have to call the script like python yourscript.py the_height.
If you want to call it like python myscript.py --height 222 then you must do
parser.add_argument("--height", action="store")
args_namespace = parser.parse_args()
print(args_namespace.height)
I am new to python. I tried to run below python code in pycharm but without taking user input it exits. Any help?
import math
import argparse
parse = argparse.ArgumentParser(description='calculate the area of a cylinder')
parse.add_argument('radius', type=int, help='Radius of the Cylinder')
parse.add_argument('height', type=int, help='Height of the Cylinder')
args = parse.parse_args()
def cylinder_volume(radius, height):
vol = math.pi * (radius ** 2) * (height)
return vol
if __name__ == '__main__':
print(cylinder_volume(args.radius, args.height))
age = input("take input")
print("The input is",age)
#C:\Users\manoj\venv\argparse_demo\Scripts\python.exe C:/Users/manoj/PycharmProjects/argparse_demo/new.py
#usage: new.py [-h] radius height
#new.py: error: the following arguments are required: radius, height
#Process finished with exit code 2
It seems quite a redundat use of both command line argument and input(). I think doing examples with input() take syou on a wrong path in python programming, they also make bad question of StackOverflow with undetermined/unreplicable results. I was trying to make this point here earlier, but with very limited support from community.
In this particular case the line swith input seem very redundant. You just seem to learn passing the arguments through command line and then you want to play with input() - which seems a step back.
argparse takes only sys.argv arguments. To use argparse, you need to specify your arguments through command line, like: python new.py argument1 argument2
If you want to use input() for interactive purposes, pass the return value of input() to your function and don't use argparse.
I am trying to run code using user's args as:
parser = argparse.ArgumentParser()
args = parser.parse_args()
parser = argparse.ArgumentParser(description='Script for running daily batch jobs for T3000 Project')
parser.add_argument("from_date", help='date in string yyyy-mm-dd', default='2017-10-1')
parser.add_argument("to_date", help='date in string yyyy-mm-dd', default='2017-12-31')
args = parser.parse_args()
main(
from_date=args.from_date,
to_date=args.to_date
)
While passing the arguments, I am following the path in Pycharm as: Run->Edit Configurations->Script Parameters: "2017-10-31" "2017-11-1"
I am getting error:
driver.py: error: unrecognized arguments: 2017-10-31 2017-11-1
Process finished with exit code 2
I have seen the link, which seems similar to my problem, but given solution didn't work for me. I am missing something I guess. Help will be appreciated.
Your first argument parser:
parser = argparse.ArgumentParser()
args = parser.parse_args()
is expecting no arguments, but you have passed in two. That is where the complaint is coming from. The solution is simply to remove those two lines - I don't know why you have them there in the first place.
I dont understand the comment by #lxop, I had the same error but I require both these lines. My code is the same apart from variables as the code used in the original question.
The solution for me is to set up my parameter in Pycharm as follows, quotations around the parameter are optional. I get the error when -o is missing.
-o filename.csv
My argparse setup line is
parser.add_argument("-o", "--outfile",
help="Enter the name of a .csv file to contain output or default of radarOutTemp.csv will be used",
default="radarOutTemp.csv")
I am trying to get a Python script to work regardless when an argument has been passed or not.
The goal is to make the script functional as "MyPython.py" and "MyPython.py 5" should be able to work. If no argument has been passed, then the argument should be 0.
The variable imported_number should by default be 0 but if an argument has been detected, then it should take whatever number the user has passed.
import argparse
imported_number=0
parser = argparse.ArgumentParser()
parser.add_argument("opt_number", type=int, help="Provide a number please")
args = parser.parse_args()
if args.opt_number > 0:
imported_number=args.opt_number
print "You provided me with the number " + imported_number
print "You provided me with the number {}".format(args.opt_number)
else:
print "You did not provide me with any number. Taking the default value, which is " + imported_number
Unfortunately I am getting the error: too few arguments error message.
Does anyone know of good and automated methods to get this task done? I'd appreciate it.
Use nargs, default, const like this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("opt_number", type=int, help="Provide a number please",
nargs='?', default=0, const=0)
args = parser.parse_args()
print(args)
Your opt_number will be initialized with 0 when no argument is provided.
You can make your script a function that accepts and argument passed to it.
import sys
def your_function(imported_number=0):
#your code
if __name__=='__main__':
try:
imported_number=sys.argv[1]
except:
pass
your_function(imported_number)