SystemExit: 2 error when calling parse_args() in iPython Notebook

2024/10/2 18:28:28

I'm learning to use Python and scikit-learn and executed the following block of codes (originally from http://scikit-learn.org/stable/auto_examples/document_classification_20newsgroups.html#example-document-classification-20newsgroups-py) in iPython notebook (using Python 2.7):

from __future__ import print_function
from optparse import OptionParser# parse commandline arguments
op = OptionParser()
op.add_option("--report",action="store_true", dest="print_report",help="Print a detailed classification report.")
op.add_option("--chi2_select",action="store", type="int", dest="select_chi2",help="Select some number of features using a chi-squared test")
op.add_option("--confusion_matrix",action="store_true", dest="print_cm",help="Print the confusion matrix.")
op.add_option("--top10",action="store_true", dest="print_top10",help="Print ten most discriminative terms per class"" for every classifier.")
op.add_option("--all_categories",action="store_true", dest="all_categories",help="Whether to use all categories or not.")
op.add_option("--use_hashing",action="store_true",help="Use a hashing vectorizer.")
op.add_option("--n_features",action="store", type=int, default=2 ** 16,help="n_features when using the hashing vectorizer.")
op.add_option("--filtered",action="store_true",help="Remove newsgroup information that is easily overfit: ""headers, signatures, and quoting.")(opts, args) = op.parse_args()
if len(args) > 0:op.error("this script takes no arguments.")sys.exit(1)

Upon running the codes, I encountered the following error:

An exception has occurred, use %tb to see the full traceback.SystemExit: 2Usage: -c [options]-c: error: no such option: -f
To exit: use 'exit', 'quit', or Ctrl-D.

I followed the instruction and executed %tb, and the following appeared:

---------------------------------------------------------------------------
SystemExit                                Traceback (most recent call last)
<ipython-input-1-d44fadf3a28b> in <module>()37                    "headers, signatures, and quoting.")38 
---> 39 (opts, args) = op.parse_args()40 if len(args) > 0:41     op.error("this script takes no arguments.")C:\Anaconda\lib\optparse.pyc in parse_args(self, args, values)1399             stop = self._process_args(largs, rargs, values)1400         except (BadOptionError, OptionValueError), err:
-> 1401             self.error(str(err))1402 1403         args = largs + rargsC:\Anaconda\lib\optparse.pyc in error(self, msg)1581         """1582         self.print_usage(sys.stderr)
-> 1583         self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))1584 1585     def get_usage(self):C:\Anaconda\lib\optparse.pyc in exit(self, status, msg)1571         if msg:1572             sys.stderr.write(msg)
-> 1573         sys.exit(status)1574 1575     def error(self, msg):SystemExit: 2

I understand that optparse has been deprecated in favour of argparse, but as I wanted to understand the tutorial block by block, I was hoping I can run the codes within iPython notebook to get a feel of how it works. It seems that someone else had this problem previously but there wasn't a solution proposed.

Is there a way to address this error so I can run the tutorial codes from within iPython notebook?

Answer

You can add the arguments you need as a list of strings

(opts, args) = op.parse_args(["--report"])
https://en.xdnf.cn/q/70815.html

Related Q&A

How to convert numpy datetime64 [ns] to python datetime?

I need to convert dates from pandas frame values in the separate function:def myfunc(lat, lon, when):ts = (when - np.datetime64(1970-01-01T00:00:00Z,s)) / np.timedelta64(1, s)date = datetime.datetime.u…

how to remove a back slash from a JSON file

I want to create a json file like this:{"946705035":4,"946706692":4 ...}I am taking a column that only contains Unix Timestamp and group them.result = data[Last_Modified_Date_unixti…

Can sockets be used to connect multiple computers on different networks in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 6…

python logging close and application exit

I am using the logging module in an application and it occurred to me that it would be neat if the logging module supported a method which would gracefully close file handles etc and then close the app…

LookupError: unknown encoding: cp0

I am on window 7, python 2.7.2, pandas 0.11.0, django 1.4, wsgi and apache 2.2. I have a pandas script that works fine if I run it directly with python and also works in ipython with %run. However, w…

Cant activate Python venv in Windows 10

I created a virtual environment with python -m venv myenv from the command prompt, but I dont know how to activate it. I tried executing activate.bat from the command prompt but it does not activate.In…

Opening file path not working in python [duplicate]

This question already has answers here:open() gives FileNotFoundError / IOError: [Errno 2] No such file or directory(11 answers)Closed last year.I am writing a database program and personica is my test…

Cython: Segmentation Fault Using API Embedding Cython to C

Im trying to embed Cython code into C following Oreilly Cython book chapter 8. I found this paragraph on Cythons documentation but still dont know what should I do:If the C code wanting to use these fu…

Computing AUC and ROC curve from multi-class data in scikit-learn (sklearn)?

I am trying to use the scikit-learn module to compute AUC and plot ROC curves for the output of three different classifiers to compare their performance. I am very new to this topic, and I am struggli…

Nested dictionary

I am working on some FASTA-like sequences (not FASTA, but something I have defined thats similar for some culled PDB from the PISCES server).I have a question. I have a small no of sequences called nCa…