使用argparse和IPython运行模块

2024-06-26 13:10:11 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这个文件:

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--foo', action='store_true')
    args = parser.parse_args()
    print(args)

如果我用Python运行它,它工作得很好:

% python -m t --foo
Namespace(foo=True)

但是,使用IPython运行它时,会出现一个错误:

% ipython -m t --foo
usage: ipython [-h] [--debug] [--quiet] [--init] [--autoindent] [--no-autoindent] [--automagic] [--no-automagic] [--pdb] [--no-pdb] [--pprint]
               [--no-pprint] [--color-info] [--no-color-info] [--ignore-cwd] [--no-ignore-cwd] [--nosep] [--autoedit-syntax]
               [--no-autoedit-syntax] [--simple-prompt] [--no-simple-prompt] [--banner] [--no-banner] [--confirm-exit] [--no-confirm-exit]
               [--term-title] [--no-term-title] [--classic] [--quick] [-i] [--profile-dir ProfileDir.location]
               [--profile TerminalIPythonApp.profile] [--ipython-dir TerminalIPythonApp.ipython_dir] [--log-level TerminalIPythonApp.log_level]
               [--config TerminalIPythonApp.extra_config_file] [--autocall TerminalInteractiveShell.autocall]
               [--colors TerminalInteractiveShell.colors] [--logfile TerminalInteractiveShell.logfile]
               [--logappend TerminalInteractiveShell.logappend] [-c TerminalIPythonApp.code_to_run] [-m TerminalIPythonApp.module_to_run]
               [--ext TerminalIPythonApp.extra_extensions] [--gui TerminalIPythonApp.gui] [--pylab [TerminalIPythonApp.pylab]]
               [--matplotlib [TerminalIPythonApp.matplotlib]] [--cache-size TerminalInteractiveShell.cache_size]
               [extra_args [extra_args ...]]
ipython: error: argument --foo: expected one argument

如何使用IPython运行它

(我的最终目标是在脚本中运行并能够访问正在运行的IPython内核)


Tags: noparserfoodiripythonargparseargsprofile