如何将命令行参数传递给ipython

34

当我使用ipython时,有没有办法通过命令行向我的Python脚本传递参数?理想情况下,我想这样调用我的脚本:

ipython -i script.py --argument blah

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

Translated:

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


通常情况下,您会使用argparse。但在使用ipython时不确定。 - msvalkon
1
但我猜argparse也使用sys.argv来解析参数。 - adrin
1个回答

63

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

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']

2
你如何在不指定要运行的文件的情况下完成它? - rjurney
1
@rjurney,请使用 ipython -i arg1 arg2 - Omid Raha
--本身是否有语义意义,类似终端中的|>,还是仅仅是惯例? - TankorSmash
@TankorSmash 只是一种约定。如果你查看 argv,你会发现它只是列在另一个参数中。请注意,git 在这方面使用得非常广泛。 - Nathan Chappell

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