Reputation: 1724
I have a code that takes the command-line arguments into a parser
and modifies some configuration settings. Something like this:
command:
python mycode.py --config-file "some_file.yaml" SOMETHING.subsetting_a 2 SOMETHING.subsetting_b 3
and then it does:
import argparse
parser = argparse.ArgumentParser(description="Some description here")
parser.add_argument(
"--config-file",
default="",
metavar="FILE",
help="path to config file",
type=str,
)
//some more 'add_argument' lines here
args = parser.parse_args()
But as I am using jupyter notebook, it would be easier to provide the arguments directly to the parser, as if they come from the command-line. How can I create a string containing the command (as mentioned above) and pass it to parser
?
Upvotes: 2
Views: 9603
Reputation: 1724
Note: As @ShadowRanger mentioned, there is no need to use sys.argv
. See his response.
One way is to use sys.argv
to mimic the command-line arguments:
import sys
sys.argv = [
"--config-file" , "some_file.yaml",
"SOMETHING.subsetting_a" , "2",
"SOMETHING.subsetting_b" , "3"]
args = parser.parse_args(sys.argv)
The content of args is something liek this:
> Namespace(config_file='some_file.yaml', opts=['SOMETHING.subsetting_a', '2', 'SOMETHING.subsetting_b', '3')
which is similar to the output of print(parser.parse_args())
.
Upvotes: 1
Reputation: 155683
parse_args
's first optional argument is the list of arguments to parse, the signature is:
ArgumentParser.parse_args(args=None, namespace=None)
It just takes args
from sys.argv
if you don't provide it.
So just call it as:
args = parser.parse_args(['mycode.py', '--config-file', "some_file.yaml", 'SOMETHING.subsetting_a', '2', 'SOMETHING.subsetting_a'])
(with the list
containing whatever you like instead) and it will use it instead of sys.argv
.
Upvotes: 3