问题
Whenever I use parser.parse_args()
, the kernel crashes. For instance:
import argparse
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument("--return_counts", type=bool, default=True)
opt = parser.parse_args()
arr = np.random.randint(0, 10, 100)
It gives this error:
usage: pydevconsole.py [-h] [--return_counts RETURN_COUNTS]
pydevconsole.py: error: unrecognized arguments: --mode=client --port=52085
But, if I use parser.parse_known_args()
, it works.
import argparse
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument("--return_counts", type=bool, default=True)
opt, unknown = parser.parse_known_args()
arr = np.random.randint(0, 10, 100)
It works, and opt
gives this:
print(opt)
Out[3]: Namespace(return_counts=True)
And unknown
gives this:
Out[4]: ['--mode=client', '--port=52162']
Can someone explain the sorcery behind this?
回答1:
It seems like you aren't providing the correct arguments to your command line. You need to add more arguments to the parser.
import argparse
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument("--return_counts", type=bool, default=True)
parser.add_argument("--mode", default='client')
parser.add_argument("--port", default=52162)
args = parser.parse_args()
Now you can use python3 pydevconsole.py --return_counts True --mode client --port 52162
in the command line and you will see:
print(args.return_counts) # True
print(args.mode) # client
print(args.port) # 52162
回答2:
parse_args
and parse_known_args
use sys.argv
unless you pass an argument to them (for instance parser.parse_args(['a', 'b', 'c'])
)
whatever thing you started (presumably ipython / jupyter / etc.) was started with --mode=client --port=52162
The reason parse_known_args
doesn't produce an error and exit is because it only parses the known arguments -- and not producing an error for unknown arguments (it can still produce errors for known arguments, for instance if they're the wrong type)
来源:https://stackoverflow.com/questions/59081228/argparser-returns-mode-client-port-52085-and-crashes