簡體   English   中英

如何將文件加載到 python 控制台?

[英]How do I load a file into the python console?

我有幾行 python 代碼,我不斷將它們復制/粘貼到 python 控制台中。 load命令或我可以運行的東西嗎? 例如load file.py

對於 Python 2,試試execfile (參見 Python 3 的其他答案)

execfile('file.py')

用法示例:
讓我們使用“copy con”快速創建一個小腳本文件...

C:\junk>copy con execfile_example.py
a = [9, 42, 888]
b = len(a)
^Z
        1 file(s) copied.

...然后讓我們像這樣加載這個腳本:

C:\junk>\python27\python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile('execfile_example.py')
>>> a
[9, 42, 888]
>>> b
3
>>>

從手冊頁:

-i 當腳本作為第一個參數傳遞或使用 -c 選項時,在執行腳本或命令后進入交互模式。 它不讀取 $PYTHONSTARTUP 文件。 當腳本引發異常時,這對於檢查全局變量或堆棧跟蹤非常有用。

所以這應該做你想做的:

python -i file.py

Python 3:新的 exec (已刪除 execfile)

execfile 解決方案僅對 Python 2 有效。Python 3 刪除了 execfile 函數 - 並將 exec 語句提升為內置通用函數。 正如 Python 3.0 的更新日志和 Hi-Angels 評論中的評論所暗示的那樣:

exec(open(<filename.py>).read())

代替

execfile(<filename.py>)

從 shell 命令行:

python file.py

從 Python 命令行

import file

或者

from file import *

您可以只使用導入語句:

from file import *

因此,例如,如果您有一個名為my_script.py的文件,您可以像這樣加載它:

from my_script import *

在要導入的文件所在的文件夾中打開命令提示符。 當你輸入 'python' 時,python 終端將被打開。 現在你可以使用

import script_name
注意:導入時不要使用 .py 擴展名。
如何在特定位置打開 cmd 窗口?

如果你使用 IPython,你可以簡單地運行:

%load path/to/your/file.py

請參閱http://ipython.org/ipython-doc/rel-1.1.0/interactive/tutorial.html

如果您的path環境變量包含 Python(例如C:\\Python27\\ ),您可以簡單地從 Windows 命令行 (cmd) 運行您的 py 文件。 如何在這里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM