My code looks like this:
parser.add_argument('-i', '--input', help='Input path/to/file.csv', required=True)
parser.add_argument('-oh', '--output-html', help='Output path/to/confusion_matrix.html', required=True)
parser.add_argument('-oc', '--output-csv', help='Output path/to/confusion_matrix.csv', required=True)
args = parser.parse_args()
....
y_true = pd.Series(true_data, name="Actual")
y_pred = pd.Series(pred_data, name="Predicted")
df_confusion = pd.crosstab(y_true, y_pred)
df_confusion.to_html(args.output-html)
df_confusion.to_csv(args.output-csv)
When i try to run it, it gives me this error:
df_confusion.to_html(args.output-html)
AttributeError: 'Namespace' object has no attribute 'output'
However, if i change from
df_confusion.to_html(args.output-html)
To
df_confusion.to_html(args.output)
It works as it should. Can anyone explain why it doesn't work, and how can i make it work with args.output-html?
By default (ie if you don't provide dest kwarg to add_argument) it changes - to _ when creating the attribute since Python attributes can't contain the character - (as a matter of fact they can, but then they are only accessible by using getattr).
It means that you should change args.output-html to args.output_html, and args.output-csv to args.output_csv.
Related
I am attempting to develop an application using argparse module in Python3. I am getting the above error on when attempting to call the function parse._intermixed_args(some_string).
parser = argparse.ArgumentParser(prog='string',description='description')
parser.add_argument('--optional', nargs='+', type=int, help='help text')
parser.add_argument('name', help='help text')
if len(commands) > 0:
args=parser.parse_intermixed_args(commands)
According to the docs parse_intermixed_args was introduced in Python 3.7. You must be using an earlier version.
I have defined this method/function in a google colab cell
[5]:def lstm_model2(input_features, timesteps, regularizers=regularizers, batch_size=10):
model = Sequential()
model.add(LSTM(15, batch_input_shape=(batch_size, timesteps,
input_features), stateful=True,
recurrent_regularizer=regularizers))
model.add(Dense(1))
model.compile(loss='mae', optimizer='adam')
return model
I want to pass this method to a script I am executing in the next cell using argparse.
[6]:!python statefulv2.py --model=lstm_model2
I tried an approach similar to type argument in argparse like defining a identically named abstract method inside the statefulv2.py script so that argparse.add_argument('--model', help='LSTM model', type=lstm_model2, required=True) can be written inside statefulv2.py But this raises an invalid argument error.
Is there a neat way to pass methods as arguments in argparse?
The reason for keeping the method outside is to edit it for trying differeny functions since GoogleColab does not provide separate editor for changing model in a separate file.
It's best that you don't try to pass arguments like that. Stick to the basic types. An alternative would be to store the different models in a file like models.py, such as:
def lstm_model1(...):
# Definition of model1
def lstm_model2(...):
# Definition of model2
and so on.
In statefulv2.py you can have:
import models
import argparse
parser = ...
parser.add_argument('-m', "--model", help='LSTM model',
type=str, choices=['model1', 'model2'], required=True)
model_dict = {'model1': models.lstm_model1(...),
'model2': models.lstm_model2(...)}
args = parser.parse_args()
my_model = model_dict[args.model]
EDIT: If saving model to file is not allowed.
In case you absolutely have to find a workaround, you can save the code in a buffer file which can be read into statefulv2.py as an argument of type open. Here is a demo:
In your Colab cell, you write the function code in a string:
def save_code_to_file():
func_string = """
def lstm_model3():
print ("Hey!")
"""
with open("buffer", "w") as f:
f.write(func_string)
In statefulv2.py, you can have:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-m', "--model", help='LSTM model', type=open, required=True)
args = parser.parse_args()
lines = args.model.readlines()
model_def = ""
for line in lines:
model_def += line
exec(model_def)
lstm_model3()
Output (this is in iPython, change it accordingly for Colab):
In [25]: %run statefulv2.py -m buffer
Hey!
I'm trying to access to the "resources" folder with the ArgumentParser.
This code and the "resources" folder are in the same folder...
Just to try to run the code, I've put a print function in the predict function. However this error occurs:
predict.py: error: the following arguments are required: resources_path
How can I fix it?
from argparse import ArgumentParser
def parse_args():
parser = ArgumentParser()
parser.add_argument("resources_path", help='/resources')
return parser.parse_args()
def predict(resources_path):
print(resources_path)
pass
if __name__ == '__main__':
args = parse_args()
predict(args.resources_path)
I am guessing from your error message that you are trying to call your program like this:
python predict.py
The argument parser by default gets the arguments from sys.argv, i.e. the command line. You'll have to pass it yourself like this:
python predict.py resources
It's possible that you want the resources argument to default to ./resources if you don't pass anything. (And I further assume you want ./resources, not /resources.) There's a keyword argument for that:
....
parser.add_argument('resources_path', default='./resources')
...
Day three of learning python.
I'm attempting to understand how to pass flags from the command line and call a function with that flag. However, I'm getting the following error:
Traceback (most recent call last):
File "main.py", line 18, in <module>
parser.add_option("-l", action="callback", callback=printLogs)
AttributeError: 'ArgumentParser' object has no attribute 'add_option'
The code is here:
import argparse
def printLogs():
print("logs!")
parser = argparse.ArgumentParser()
parser.add_argument('-e','--entry', type=str, help='New entry',required=False)
parser.add_option("-l", action="callback", callback=printLogs)
args = parser.parse_args()
I can understand that parser.add_option doesn't exist for parser. This much is clear. I can also see that the OptionParser has been deprecated as per this link. So, OptionParser is out.
The question being: How do I parse the -l argument such that the printLogs function is called when its passed?
The way I would implement this is:
import argparse
def printLogs():
print("logs!")
parser = argparse.ArgumentParser()
parser.add_argument('-e','--entry', type=str, help='New entry')
parser.add_argument("-l", action="store_true", help='print logs')
args = parser.parse_args()
if args.l:
printLogs()
The primary purpose of argparse is to parse the input (sys.argv), and give you a set of argument values (args is a simple namespace object). callbacks is a optparse concept that have not been included in argparse.
The FooAction example in the docs, http://docs.python.org/3.4/library/argparse.html#action, does something like this optparse callback. It prints some information when called, and then does the important thing - set a value in the namespace.
When I run this code I get
AttributeError: 'ArgumentParser' object has no attribute 'max_seed'
Here's the code
import argparse
import ConfigParser
CFG_FILE='/my.cfg'
# Get command line arguments
args = argparse.ArgumentParser()
args.add_argument('verb', choices=['new'])
args.add_argument('--max_seed', type=int, default=1000)
args.add_argument('--cmdline')
args.parse_args()
if args.max_seed:
pass
if args.cmdline:
pass
My source file is called "fuzz.py"
You should first initialize the parser and arguments and only then get the actual arguments from parse_args() (see example from the docs):
import argparse
import ConfigParser
CFG_FILE='/my.cfg'
# Get command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('verb', choices=['new'])
parser.add_argument('--max_seed', type=int, default=1000)
parser.add_argument('--cmdline')
args = parser.parse_args()
if args.max_seed:
pass
if args.cmdline:
pass
Hope that helps.
If you use argparse parsed arguments inside another class (somewhere you do self.args = parser.parse_args() ), you might need to explicitly tell your lint parser to ignore Namespace type checking. As told by #frans at Avoid Pylint warning E1101: 'Instance of .. has no .. member' for class with dynamic attributes
:
Just to provide the answer that works for me now - as [The
Compiler][1] suggested you can add a rule for the problematic class in
your projects .pylintrc:
[TYPECHECK]
ignored-classes=Namespace
[1]: https://stackoverflow.com/users/2085149/the-compiler