1. 程式人生 > 程式設計 >Python 指令碼的三種執行方式小結

Python 指令碼的三種執行方式小結

1.互動模式下執行 Python,這種模式下,無需建立指令碼檔案,直接在 Python直譯器的互動模式下編寫對應的 Python 語句即可。

1)開啟互動模式的方式:

Windows下:

在開始選單找到“命令提示符”,開啟,就進入到命令列模式:

在命令列模式輸入: python 即可進入 Python 的互動模式

Linux 下:

直接在終端輸入 python,如果是按裝了 python3 ,則根據自己建的軟連線的名字進入對應版本的 Python 互動環境,例如我建立軟連線使用的 python3,這輸入 python3。

2)退出互動模式,直接輸入 exit() 即可。

Windows下:

Linux 下:

3)在互動模式下輸出: Hello World!

Windows:

Linux:

2.通過指令碼輸出

通過文字編輯器,編寫指令碼檔案,命名為 hello.py,在命令列模式下輸入 python hello.py 即可

Windows:

Linux:

[Vicky@localhost code]$ touch hello.py
[Vicky@localhost code]$ vi hello.py 
[Vicky@localhost code]$ python3 hello.py 
Hello World!

這種方式,要注意指令碼檔案所在路徑,如果當前工作路徑和指令碼檔案不在同一路徑下,則要進入 指令碼檔案所在路徑,或者給出指令碼檔案的完整路徑。

1)進入指令碼檔案所在路徑下執行

C:\Windows\System32>G:
G:\test>python hello.py
Hello World!

2)給出指令碼檔案的完整路徑

C:\Windows\System32>python G:\test\hello.py
Hello World!

3.在指令碼檔案中指定 python 程式所在路徑,修改檔案為可執行檔案,然後直接執行檔案

Linux下:

1)修改檔案,新增 #!/usr/bin/python3

[Vicky@localhost code]$ vi hello.py 
[Vicky@localhost code]$ cat hello.py 
#!/usr/bin/python3
print("Hello World!")

2)修改檔案許可權,新增可執行許可權

[Vicky@localhost code]$ chmod u+x hello.py 
[Vicky@localhost code]$ ls -la hello.py 
-rwxrw-r--. 1 Vicky Vicky 41 10月 19 15:40 hello.py

3)執行

[Vicky@localhost code]$ ./hello.py 
Hello World!

此種方式執行的時候,一定要在指令碼檔案中指定直譯器,否則無法直接執行指令碼檔案

[Vicky@localhost code]$ cat hello.py 
print("Hello World!")
[Vicky@localhost code]$ ls -la hello.py 
-rwxrw-r--. 1 Vicky Vicky 22 10月 19 15:40 hello.py
[Vicky@localhost code]$ ./hello.py 
./hello.py:行1: 未預期的符號 `"Hello World!"' 附近有語法錯誤
./hello.py:行1: `print("Hello World!")'

4.互動模式和指令碼檔案方式的比較

1)在互動模式下,會自動打印出運算結果,而通過指令碼檔案的方式不會

互動模式:

[fanya@localhost code]$ python3
Python 3.6.5 (default,Oct 19 2018,10:46:59) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help","copyright","credits" or "license" for more information.
>>> 100+200
300
>>> exit()

指令碼檔案:

[fanya@localhost code]$ vi cal.py 
[fanya@localhost code]$ cat cal.py 
100+200
[fanya@localhost code]$ python3 cal.py 
[fanya@localhost code]$ 

可見沒有任何輸出,此時要想輸出,必須使用 print 函式進行列印。

[fanya@localhost code]$ vi cal.py 
[fanya@localhost code]$ cat cal.py 
print(100+200)
[fanya@localhost code]$ python3 cal.py 
300
[fanya@localhost code]$ 

2)在互動模式下,每次輸入的語句不會被儲存,退出互動環境之後即消失,但是通過指令碼檔案我們可以儲存我們寫過的所有語句。所以通常都是通過編寫 指令碼檔案的方式來編寫 Python 程式碼。

注意:在編寫指令碼檔案的時候不要使用 word 和 windows 自帶的筆記本,因為他們在儲存的時候會儲存為 utf-8 BOM 格式,這會導致指令碼執行錯誤。可以使用 sublime,editplus,notepad++

以上這篇Python 指令碼的三種執行方式小結就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。