1.交互模式下執(zhí)行 Python,這種模式下,無需創(chuàng)建腳本文件,直接在 Python解釋器的交互模式下編寫對應的 Python 語句即可。
1)打開交互模式的方式:
Windows下:
在開始菜單找到“命令提示符”,打開,就進入到命令行模式:
在命令行模式輸入: python 即可進入 Python 的交互模式
Linux 下:
直接在終端輸入 python,如果是按裝了 python3 ,則根據(jù)自己建的軟連接的名字進入對應版本的 Python 交互環(huán)境,例如我建立軟連接使用的 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)進入腳本文件所在路徑下執(zhí)行
C:/Windows/System32>G:G:/test>python hello.pyHello World!
2)給出腳本文件的完整路徑
C:/Windows/System32>python G:/test/hello.pyHello World!
3.在腳本文件中指定 python 程序所在路徑,修改文件為可執(zhí)行文件,然后直接運行文件
Linux下:
1)修改文件,添加 #!/usr/bin/python3
[Vicky@localhost code]$ vi hello.py [Vicky@localhost code]$ cat hello.py #!/usr/bin/python3print("Hello World!")
2)修改文件權(quán)限,添加可執(zhí)行權(quán)限
[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!
此種方式執(zhí)行的時候,一定要在腳本文件中指定解釋器,否則無法直接運行腳本文件
[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)在交互模式下,會自動打印出運算結(jié)果,而通過腳本文件的方式不會
新聞熱點
疑難解答