2014-05-25 41 views

回答

1

如果要啓動Python的控制檯和具有執行的文件,所以它的變量是提供給你,用-i

$ cat foo.py 
a = [1,2,3] 
b = 42 
print('Hello world') 
$ python -i foo.py 
Hello world 
>>> a 
[1, 2, 3] 
>>> b 
42 
>>> quit() 

如果你已經在解釋器中,用execfile,就像這樣:

$ python 
Python 2.7.6 (default, Apr 9 2014, 11:48:52) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> execfile('foo.py') 
Hello world 
>>> a 
[1, 2, 3] 
>>> b 
42 

如果你只是想用從文件的一些變量,使用import,像這樣:

>>> from foo import a,b 
Hello world 
>>> a 
[1, 2, 3] 
>>> b 
42 

請注意,這將執行該文件,這就是爲什麼您看到Hello world打印。

1

當然。假設你有script.py,它有函數foo()。轉到相應的目錄,並通過運行蟒蛇

>>> import script 
>>> script.foo() 

作爲一個側面說明啓動空閒,我強烈希望作爲的IPython我選擇的閒置。在這個例子中,如果你輸入「script」,它會顯示所有可用的選項。然後選項卡。 IPython強烈模仿IDLE中的命令行行爲(例如運行ls)。

相關問題