2014-03-25 20 views
19

有什么方法可以通过命令行将参数传递给我的python脚本,同时使用ipython?理想我想打电话给我的脚本:如何将命令行参数传递给ipython

ipython -i script.py --argument blah 

,我希望能有--argumentblah在我sys.argv上市。

+0

通常你会使用[argparse](HTTP ://docs.python.org/3.4/library/argparse.html)。使用ipython时不知道。 – msvalkon

+1

但我猜'argparse'也使用'sys.argv'来解析参数。 – adrin

回答

36

才可以使用一个--多个选项:

帮助 Ipython
ipython script.py -- --argument blah 

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

相关问题