Python運行方法詳解
1.IDLE
1.1 新建file后選擇路徑存儲,快捷鍵F5在shell中運行,好處是容易編輯,且可以保存,關閉shell后依然存在
def say_hello(you):
print(f"hello {you}!")
def say_bye(you):
print(f"bye {you}!")
1.2 直接在shell中運行,好處是運行方便,coding中調試不確定的語法,或者做些debug。
2.Terminal (Linux/Mac OS的shell)
2.1 Terminal中使用python/python3命令運行.py文件,例如課上編輯的say_something.py,運行命令是python3 say_something.py
2.2 Terminal中輸入python/python3命令
(1)如果current working directory下包含要運行的文件,則可以直接import .py文件。
import say_something
say_something.say_hello("Jupyter")
>>> Hello Jupiter!
from say_something import say_hello
#只import了函數say_hello,其他函數無法運行
say_hello("Jupyter")
>>> Hello Jupiter!
from say_something import *
#*代表wild card,import了say_something的所有函數,都可以運行
say_hello("Jupyter")
>>> Hello Jupyter!
say_bye("Jupyter")
>>> Bye Jupyter!
(2)如果current working directory下不包含要運行的文件,則可以把文件的路徑寫入python的path讀取list中。
查看python的path讀取list,先打開terminal
方法1:
python3
>>>from sys import path
>>>path
方法2:
echo $PATH
MAC增加sys.path的路徑,先打開terminal
mkdir -p Python/3.6/lib/python/site-packages
#創建路徑
echo '路徑' >> Python/3.6/lib/python/site-packages/my_path.pth
#將'路徑' 添加到my_path.pth文件中,例如'路徑'是'/Users/comp9021/Documents
import '路徑' as abc
#如果‘路徑’過長,可以使用上面的語法用另一個變量替代,例如課上import 'Lectures.Lecture_2.say_something as ss
2.3 Terminal中的vi(visual)界面
vi界面基本操作,命令":q"直接退出,命令":wq"退出保存
創建一個python的命令say_hello
vi say_hello
#進入vi界面
!#/usr/local/bin/python3 #下文用python語言編譯
print("Hello world!")
:wq
chmod a+x say_hello
#賦予say_hello運行的權限
往期回顧
COMP9021 Principles of Programming WEEK1 Optional
COMP9021 Principles of Programming WEEK1