在 iPython Notebook 中调用parse_args()时出现SystemExit: 2错误

7
我正在学习使用Python和scikit-learn,并在iPython笔记本中执行以下代码块(最初来自http://scikit-learn.org/stable/auto_examples/document_classification_20newsgroups.html#example-document-classification-20newsgroups-py)(使用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)

在运行代码时,我遇到了以下错误:
An exception has occurred, use %tb to see the full traceback.

SystemExit: 2


Usage: -c [options]

-c: error: no such option: -f
To exit: use 'exit', 'quit', or Ctrl-D.

我按照指示执行了%tb命令,出现了以下内容:

---------------------------------------------------------------------------
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 + rargs

C:\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

我知道optparse已经被弃用,现在使用argparse代替它,但是我想逐块理解教程,希望能够在iPython笔记本中运行代码,以便更好地了解它的工作原理。似乎之前有人遇到过这个问题,但没有提出解决方案。
是否有一种方法可以解决这个错误,以便我可以在iPython笔记本中运行教程代码?

可能是 SystemExit: 2 error when calling parse_args() 的重复问题。 - daphtdazz
在我的情况下,我的代码可以在其他IDE(同一台电脑)和另一台电脑上的Jupyter笔记本中运行。 - user3226167
3个回答

2
[快速解决方案] 在代码中添加一个虚拟解析器参数。
op.add_option('-f')

2
您可以将所需的参数作为字符串列表添加
(opts, args) = op.parse_args(["--report"])

0

正如您所看到的 " error: no such option: -f ",因此您需要添加:

op.add_option("-f", required=False)

这个在你的情况下可以工作:
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.")
op.add_option("-f", required=False)

(opts, args) = op.parse_args()
    if len(args) > 0:
    op.error("this script takes no arguments.")
    sys.exit(1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接