Ubuntu 14.04官方沒提供套件安裝Python3.5,需增加來源
sudo add-apt-repository ppa:fkrull/deadsnakes
sudo apt-get update
sudo apt-get install python3.5
在shell下輸入啟動REPL(Read-Eval-Print-Loop),俗稱python shell
python3.5
另外Ubuntu的REPL支援Tab鍵自動完成(auto-complete)
>>>1+1
2
>>>_
2
>>>1+_
3
>>> 'Hello world'
'Hello world'
>>>print(_)
Hello world
>>>print('Hello world')
Hello world
在Python 2的時候print並不需要小括號
>>>help()
進入說明書
可輸入keywords, modules...等等
>>>help(print)
某函數的說明
>>>quit()
離開REPL,Ctrl+D也可以離開
Python anywhere可以線上跑python小程式,註冊beginner帳號即可
https://www.pythonanywhere.com/
>>>input()
請使用者輸入內容,如果是python2要用raw_input()
直接執行python指令,執行完就結束
python3.5 -c "print('Hello world')"
平常python的script副檔名是.py
執行script
python3.5 your_script_name.py
>>>#註解單一行
>>># coding=MS950
>>># coding:MS950
指定script的text coding類型,Windows 使用MS950或是Big5,Ubuntu用UTF-8
python抓取類型時使用的Regular expression在PEP 263中有定義是
^[ \t\v]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)
所以也很常看到有人用
>>> -*- coding: Big5 -*-
>>> name = input('名稱:')
在使用者輸入的行前面印出'名稱:'
>>> print('哈囉!', name, '!')
印出字串和變數
每個.py檔案都可以當一個模組
獲取shell的引數,要引用sys
import sys
print('Hello', sys.argv[1], '!')
引用多個模組可用, 分隔
import sys, email
有些基本的函數和模組會被列入__builtins__模組中,可以不用import直接取用,就像之前的print(), input()函數
使用dir函數可以顯示可用的內容
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
Windows
SET PYTHONPATH=C:\mypython
Ubuntu
export PYTHONPATH=/home/miro/mypython
查看目前的python path
>>>import sys
>>>sys.path
['', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages']
加入python path之後
['', '/home/miro/mypython', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages']
我們除了設定python path,也能夠動態的在python內增加路徑,python就會動態的去載入對應的模組
>>>sys.path.append('/home/yhchiu/mypython')
Question: 可以卸載模組嗎?
Answer: 只能用del來移除名稱的榜定, 例如del sys
Question: 已經載入的模組是否能夠透過修改路徑使得結果不同?
Answer: 測試的結果是不行,就算移除sys.path的內容,已經載入的模組還是可以import的近來
>>> import sys
>>> import mypy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'mypy'
>>> sys.path.append('.')
>>> sys.path
['.']
>>> import mypy
mypy.py
>>> mypy
<module 'mypy' from './mypy.py'>
>>> sys.path
['.']
>>> sys.path.clear()
>>> mypy
<module 'mypy' from './mypy.py'>
>>> del mypy
>>> import mypy
>>> mypy
<module 'mypy' from './mypy.py'>
>>> del mypy
>>> mypy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'mypy' is not defined
Question:如果兩個目錄有同一個模組名稱,兩個都能用? 不然會用哪一個?
Answer: 不能兩個都用。只會載入在sys.path中最先找到的那個模組。
要容許兩個同名稱模組,必須再前面再用目錄來分
變成a和b目錄裏面都放mypy.py,然後我們再修改一下印出的內容
>>> import sys
>>> sys.path.append(".")
>>> sys.path
['', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages', '.']
>>> import a.mypy
a/mypy.py
>>> import b.mypy
b/mypy.py
>>>
如果a,b兩個資料夾沒有加入__init__.py檔案,python3.5會視為是一種namespace而不是模組
>>> import sys
>>> sys.path.append(".")
>>> import a
>>> import b
>>> a
<module 'a' (namespace)>
>>> b
<module 'b' (namespace)>
>>> import c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'c'
>>> a.mypy
<module 'a.mypy' from '/home/yhchiu/a/mypy.py'>
>>> b.mypy
<module 'b.mypy' from '/home/yhchiu/b/mypy.py'>
>>>
a, b資料夾都加入__init__.py檔案
>>> import sys
>>> sys.path.append(".")
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>> import a
a
>>> a
<module 'a' from '/home/yhchiu/a/__init__.py'>
>>> import b
b
>>> b
<module 'b' from '/home/yhchiu/b/__init__.py'>
>>>
重新命名模組
>>> import a as c
>>> c
<module 'a' from '/home/yhchiu/a/__init__.py'>
直接匯入某名稱
>>> a = 100
>>> from b import a
b
>>> a
10
>>>
測試會蓋掉原本的變數