【问题标题】:How to pass command line arguments to ipython如何将命令行参数传递给 ipython
【发布时间】:2014-05-03 03:13:37
【问题描述】:

在使用 ipython 时,有什么方法可以通过命令行将参数传递给我的 python 脚本?理想情况下,我想将我的脚本称为:

ipython -i script.py --argument blah

我希望能够在我的sys.argv 中列出--argumentblah

【问题讨论】:

  • 通常你会使用argparse。不知道什么时候使用 ipython。
  • 但我猜argparse 也使用sys.argv 来解析参数。

标签: python ipython


【解决方案1】:

您可以在此之前使用一个-- 更多选项:

ipython  script.py -- --argument blah

Ipython的帮助:

ipython [subcommand] [options] [-c cmd | -m mod | file] [--] [arg] ...

If invoked with no options, it executes the file and exits, passing the
remaining arguments to the script, just as if you had specified the same
command with python. You may need to specify `--` before args to be passed
to the script, to prevent IPython from attempting to parse them. If you
specify the option `-i` before the filename, it will enter an interactive
IPython session after running the script, rather than exiting.

演示:

$ cat script.py 
import sys
print(sys.argv)

$ ipython  script.py -- --argument blah
['script.py', '--argument', 'blah']

$ ipython  script.py -- arg1 arg2
['script.py', 'arg1', 'arg2']

【讨论】:

  • 不指定要运行的文件怎么办?
  • @rjurney,使用ipython -i arg1 arg2
  • -- 本身是否有任何语义含义,比如终端中的 |>,或者这只是惯例?
  • @TankorSmash 只是惯例。如果您查看 argv,您只会看到它被列为另一个参数。请注意,git 广泛使用它。
猜你喜欢
  • 2016-09-28
  • 2016-05-31
  • 2013-10-11
  • 1970-01-01
  • 2012-09-01
  • 2020-08-02
  • 2014-01-13
相关资源
最近更新 更多