The code in the IDE uses parser.parse_args()
, and an error occurs when called under jupyter.
Error:
usage: ipykernel_launcher.py [-h] [--data_dir DATA_DIR]
[--output_dir OUTPUT_DIR]
[--embedding_path EMBEDDING_PATH]
.....
ipykernel_launcher.py: error: unrecognized arguments: -f /home/xxx/.local/share/jupyter/runtime/kernel-0fad9201-af20-4945-86b4-eeafe5b0d8b2.json
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
Cause Analysis
This is because calling parser.parse_args()
will read the system parameters: sys.argv[]
, which is the correct parameter when called from the command line, and when called in jupyter notebook, the value of sys.argv
is ipykrnel_launcher.py
:
['/home/xxx/anaconda3/envs/pt/lib/python3.8/site-packages/ipykernel_launcher.py',
'-f',
'/home/xxx/.local/share/jupyter/runtime/kernel-0fad9201-af20-4945-86b4-eeafe5b0d8b2.json']
There are two solutions, one needs to modify the code, the second only needs to set sys.argv
in jupyter.
Change parser.parse_args()
to parser.parse_known_args()[0]
import argparse
parser = argparse.ArgumentParser()
args = parser.parse_known_args()[0]
Disadvantages: need to modify the code, not elegant.
Set sys.argv
in jupyter.
1.Get the correct sys.argv For example, enter the command line as:
python run.py
Its sys.argv
is:
['run.py']
Tip: You can also add
print(sys.argv)
to the running code to get it, in the following form:
import sys
print(sys.argv)
2 Modify sys.argv
Add the following code to jupyter:
import sys
sys.argv = ['run.py']
In the code, run.py
is modified to the sys.argv required by the current running code
If you don't want to modify the code, you can try the second method.