2016-07-06 60 views
1

當我以交互模式使用Ipython運行腳本時,sys.argv參數列表在執行的交互部分中與在腳本中不同。當在Ipython中處於交互模式時,sys.argv是不同的

這是一個錯誤,還是我做錯了什麼?

謝謝!

[email protected]:~$ cat test.py 
import sys 
print(sys.argv) 
temp = sys.argv 

[email protected]:~$ ipython -i test.py -- foo bar 
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
Type "copyright", "credits" or "license" for more information. 

IPython 4.2.1 -- An enhanced Interactive Python. 
?   -> Introduction and overview of IPython's features. 
%quickref -> Quick reference. 
help  -> Python's own help system. 
object? -> Details about 'object', use 'object??' for extra details. 
['/home/oskar/test.py', 'foo', 'bar'] 

In [1]: temp 
Out[1]: ['/home/oskar/test.py', 'foo', 'bar'] 

In [2]: sys.argv 
Out[2]: ['/usr/local/bin/ipython', '-i', 'test.py', '--', 'foo', 'bar'] 

回答

0

如果我只調用ipython,並期待在sys.argv我得到

In [3]: sys.argv 
Out[3]: ['/usr/bin/ipython3'] 

Out[2]看起來是一樣的 - 由外殼和Python解釋器提供的完整列表。記住我們正在與ipython進口運行的Python會話:

#!/usr/bin/env python3 
# This script was automatically generated by setup.py 
if __name__ == '__main__': 
    from IPython import start_ipython 
    start_ipython() 
/usr/bin/ipython3 (END) 

但看看ipython -h;第一段:

它執行文件並退出,通過剩餘 參數傳遞給腳本,就像您指定了與蟒蛇一樣 命令。您可能需要在將參數 傳遞給腳本之前指定--,以防止IPython試圖解析它們。

所以它明確地說,

ipython -i test.py -- foo bar 

成爲(實際上) - 或運行爲:

python test.py foo bar 

ipython代碼有處理許多解析器(如子​​)不同的論點。但它不能處理的,或者按照--被擱置,並放入你的test.py看到的sys.argv

但顯然sys.argv是不是給交互式會話。

我想你會得到相同的效果

$ipython 
In[0]: %run test.py foo bar 
... 

%run保存當前sys.argv,構建一個新的與sys.argv = [filename] + args。然後在運行您的test.py後,它將恢復sys.argv

這不是一個錯誤,你沒有做任何錯誤的 - 除了期待兩個sys.argv是相同的。看起來在一個普通的Python shell中,兩個sys.argv是相同的(沒有任何shell自己使用的選項)。

相關問題