顯示具有 [Python 學習筆記] 標籤的文章。 顯示所有文章
顯示具有 [Python 學習筆記] 標籤的文章。 顯示所有文章

2017年10月3日 星期二

[Python 學習筆記] 起步走 : 基本環境與互動 (簡介模組)

轉載自 這裡 
前言 : 
你可以撰寫一個純文字檔案,建議副檔名為.py,在當中撰寫 Python 程式碼 : 
* hello.py : 
  1. print('Hello!Python!')  
接著如下執行指令載入指令稿直譯並執行 : 
C:\Software\Python2.7.2\tutorial>python hello.py
Hello!Python!

如果你想取得命令列引數(Command line argument),則可以使用 sys.argv,例如 : 
* hello2.py : 
  1. import sys  
  2. print('Hello!' + sys.argv[1] + '!')  
要取得命令列引數,必須先以 import 語句匯入sys模組Module),命令列引數字串陣列方式收集並指定給sys.argv索引0表示為 第一個命令列引數,在Python中就是存放所執行的.py檔名,索引1則表示第二個命令列引數,依此類推. 接著如下執行指令載入指令稿直譯並執行 : 
C:\Software\Python2.7.2\tutorial>python hello2.py John
Hello!John!

模組簡介 : 
所謂模組,實際上就是個.py檔案。import語句匯入模組實際上就是載入另一個.py檔案並執行其內容。例如可先撰寫一個.py檔案 : 
* some.py : 
  1. name = 'John'  
  2. print(name)  

接著在另一個.py檔案中或指令互動模式中使用 import 語句並執行相關程式碼 : 
 

在 import some 時,實際上會載入some.py,之後將其編譯為位元碼形式,若有儲存檔案的權限,則通常會將位元碼儲存為.pyc檔案,位元碼是個與平台相依的指令格式,如果下次再匯入模組時,原始碼並沒有更動且.pyc存在,就會直接載入.pyc,減少了直譯的時間,從而加快了執行的速度。例如,在執行過以上的指令後,你可以發現 some.pyc 的存在. 使用 impor t匯入模組後,就會執行程式,所以上例中,你馬上看到 some.py 中 print 函式的結果. 模組其實也是個名稱空間,模組名稱就是檔案名稱,模組中宣告的變數或函式都是模組中的屬性,若要存取模組中的變數或函式等名稱,必須前置模組名稱,例如 some.title 這樣的名稱. 

可以使用 from import 語句「複製」出模組中的名稱,正如上面所示範的,複製出模組中的名稱是為了方便取用名稱,但設定複製出的變數,並不會影響原本模組中的變數。如果你想要知道模組中的屬性名稱,則可以使用 dir() 函式 : 
 

除了你自定義的屬性之外,還有一些內建的屬性,這之後有機會再深入介紹。你可以一次匯入兩個以上的名稱,例如 : 
from some import x, y

或者是將模組中的名稱全部匯入,例如 : 
from some import *

import 語句或 from import 語句只會在第一次匯入模組時執行模組中的程式碼,重複 import 同一個模組,並不會使得模組中的程式碼被重複執行多次,正如上例中所看到的,你並沒有看到 some.py 中的print函式重複被執行。如果你想要重新執行模組,則可以使用 imp.reload() 函式。例如 : 


附帶一提的是,如果要直接載入某個 .py 檔案來執行,則可以使用 open() 開啟 .py 檔案,之後 read() 讀取檔案,再使用 exec() 來執行,注意!這並非 import,也非 imp.reload(),只是讀取整個原始碼,再整個執行過一遍。例如 : 
 

每個 .py 檔案都是 Python 的模組,你可以將個別的功能撰寫在不同的模組中,在必要的時候以 import 語句匯入模組,就可以取用特定模組的功能,這是撰寫 Python 程式的一個中心架構! 

先前談到,可以使用dir() 查詢模組中的屬性,這邊先介紹一下 __name__ (Check Modules) 屬性。如果你使用 python 指令直接執行某個 .py 檔案,則 __name__ 屬性會被設定為 '__main__' 名稱,如果是 import 語句匯入模組,則 __name__ 會被設定為模組名稱。所以,模組的作者會為了測試自己所設計的模組,而寫下這樣的程式碼 : 
- some2.py : 
  1. def doSome(text):  
  2.     return text + '...processed...'  
  3.   
  4. def main():  
  5.     fixture = 'orz'  
  6.     print(doSome(fixture))  
  7.       
  8. if __name__ == '__main__':  
  9.     main()  
如此,只有在直接執行 some.py 時,才會呼叫 main() 函式並執行測試,若使用 import 語句匯入模組則不會! 
 

在入門階段,可以先知道的是,Python 會在 PYTHONPATH 環境變數所設定的路徑中,尋找 .py 或 .pyc 模組檔案,實際上,PYTHONPATH 環境變數的內容會被讀取,成為 sys.path 陣列中的字串元素,而這個字串所代表的路徑,正是模組檔案尋找的根據 : 

[Python 學習筆記] 函式、類別與模組 : 模組 (匯入模組)

轉載自 這裡 
前言 : 
接續 簡介模組 的內容。sys.path 陣列中的字串元素其實是由幾個來源所組成:所執行檔案(模組)的所在目錄、PYTHONPATH 環境變數的內容、標準程式庫搜尋目錄、.pth檔案中所列出的目錄. 

匯入模組 : 
例如,若在Windows上,有個模組檔案位於 C:\Software\Python3.2.2\tutorial\ClassDefModule\ImportModule,而 Python 安裝於 C:\Software\Python3.2.2\ : 
- demo.py : 
  1. import sys  
  2. print(sys.path)  
若你如下執行程式 : 
 

至於 .pth 檔案所列出的目錄,是指你可以在 Python 安裝目錄,或者是安裝目錄的 lib\site-packages 目錄中建立 .pth 檔案,當中一行一行列出搜尋模組檔案的目錄,如果該目錄確實存在,則會列為 sys.path 的內容. 例如,若在 C:\Software\Python3.2.2\ 中放置 mydir.pth,內容如下 : 
C:\tmp\test1
C:\tmp\test2

而在 C:\Software\Python3.2.2\Lib\site-packages 中放置一個 mydir.pth,內容如下 : 
C:\tmp\test3
C:\tmp\test4

如果所列的目錄確實存在,則再度執行 demo.py,會顯示如下 : 
 

import 會在 sys.path 中尋找 .py 或已編譯的 .pyc,如果 .py 尚未編譯則編譯為 .pyc,而後載入執行一次,再次 import 同一個模組並不會再執行一次模組,如果找到 .py 與 .pyc,而 .pyc 的版本並沒有比 .py 舊,則略過編譯直接執行,如果僅找到 .pyc 而沒有找到 .py,也會直接執行! 在執行時期,你可以動態地改變 sys.path 的內容,來改變搜尋模組的路徑。例如,若有個 superman.py 放在 C:\tmp\test5 中,而 superman.py 的內容如下 : 
  1. print('superman modulle')  
  2. name = 'John'  
而你執行的檔案為 : 
- test1.py : 
  1. import sys  
  2. print(sys.path, end='\n\n')  
  3.   
  4. sys.path.append('C:\\tmp\\test5')  # \\t 轉義 \t  
  5. print(sys.path, end='\n\n')  
  6.   
  7. import superman  
  8. print(superman.name)  
則執行的結果會是 : 
 

Python 的 import 是執行時期的運算,import 某個模組,就會執行該模組中定義的內容,被 import 的模組名稱會成為目前模組的變數,而被 import 的模組中的變數,就是以被 import 模組名稱為名稱空間. 

Supplement 
FAQ - set pythonpath before import statements 

2017年7月11日 星期二

[Python 文章收集] Virtual Environments

Source From Here 
Preface 
A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable. For example, you can work on a project which requires Django 1.10 while also maintaining a project which requires Django 1.8. 

virtualenv 
virtualenv is a tool to create isolated Python environments. virtualenv creates a folder which contains all the necessary executables to use the packages that a Python project would need. 
# pip install virtualenv
# virtualenv --version
15.1.0

Basic Usage 

1. Create a virtual environment for a project: 
# cd my_project_folder/
# virtualenv my_project
Using base prefix '/usr/local'
New python executable in /root/Tmp/my_project_folder/my_project/bin/python3.5
Also creating executable in /root/Tmp/my_project_folder/my_project/bin/python
Installing setuptools, pip, wheel...done.

virtualenv my_project will create a folder in the current directory which will contain the Python executable files, and a copy of the pip library which you can use to install other packages. The name of the virtual environment (in this case, it was my_project) can be anything; omitting the name will place the files in the current directory instead. 

This creates a copy of Python in whichever directory you ran the command in, placing it in a folder named my_project. You can also use the Python interpreter of your choice (like python2.7). 
// -p PYTHON_EXE, --python=PYTHON_EXE: The Python interpreter to use
# virtualenv -p /usr/bin/python2.7 my_project

or change the interpreter globally with an env variable in ~/.bashrc
# export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python2.7


2. To begin using the virtual environment, it needs to be activated: 
# env > origin_env // Save original env variables
# source my_project/bin/activate
# env > new_env
# diff origin_env new_env
7a8
OLDPWD=/root/Tmp/my_project_folder/my_project
10a12
VIRTUAL_ENV=/root/Tmp/my_project_folder/my_project
12c14
PATH=/usr/lib/jvm/java-1.8.0-openjdk/bin:/opt/groovy/bin:/root/apache-tomcat-7.0.61/bin:/opt/maven/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/opt/gradle/latest/bin:/root/bin
---
PATH=/root/Tmp/my_project_folder/my_project/bin:/usr/lib/jvm/java-1.8.0-openjdk/bin:/opt/groovy/bin:/root/apache-tomcat-7.0.61/bin:/opt/maven/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/opt/gradle/latest/bin:/root/bin
15a18
PS1=(my_project) [\u@\h \W]\$
25d27
OLDPWD=/root/Tmp/my_project_folder/my_project

The name of the current virtual environment will now appear on the left of the prompt (e.g. (my_project)Your-Computer:your_project UserName$) to let you know that it’s active. From now on, any package that you install using pip will be placed in the my_project folder, isolated from the global Python installation

Install packages as usual, for example (requests): 
# pip install requests
# p3 -c "import requests; print(requests.__version__)"
2.18.1

3. If you are done working in the virtual environment for the moment, you can deactivate it: 
# deactivate
# p3 -c "import requests; print(requests.__version__)" // The host python is installed with requests version 2.13.0
2.13.0

This puts you back to the system’s default Python interpreter with all its installed libraries. To delete a virtual environment, just delete its folder. (In this case, it would be rm -rf my_project.) After a while, though, you might end up with a lot of virtual environments littered across your system, and its possible you’ll forget their names or where they were placed. 

Other Notes 
Running virtualenv with the option --no-site-packages will not include the packages that are installed globally. This can be useful for keeping the package list clean in case it needs to be accessed later. (This is the default behavior for virtualenv 1.7 and later.) In order to keep your environment consistent, it’s a good idea to “freeze” the current state of the environment packages. To do this, run 
// freeze: Output installed packages in requirements format.
# pip freeze > requirements.txt
# tail requirements.txt
toolz==0.8.2
tqdm==4.11.2
traitlets==4.3.2
ujson==1.35
virtualenv==15.1.0
wcwidth==0.1.7
websocket-client==0.44.0
Werkzeug==0.12.2
wrapt==1.10.10
xlrd==1.0.0

This will create a requirements.txt file, which contains a simple list of all the packages in the current environment, and their respective versions. You can see the list of installed packages without the requirements format using “pip list”. Later it will be easier for a different developer (or you, if you need to re-create the environment) to install the same packages using the same versions: 
# pip install -r requirements.txt

This can help ensure consistency across installations, across deployments, and across developers. Lastly, remember to exclude the virtual environment folder from source control by adding it to the ignore list. 

virtualenvwrapper 
virtualenvwrapper provides a set of commands which makes working with virtual environments much more pleasant. It also places all your virtual environments in one place. To install (make sure virtualenv is already installed): 
# pip install virtualenvwrapper
# export WORKON_HOME=~/Envs
# source /usr/local/bin/virtualenvwrapper.sh

(Full virtualenvwrapper install instructions.

Basic Usage 

1. Create a virtual environment: 
# mkvirtualenv my_project

This creates the my_project folder inside ~/Envs

2. Work on a virtual environment: 
# workon my_project

Alternatively, you can make a project, which creates the virtual environment, and also a project directory inside $PROJECT_HOME, which is cd -ed into when you workon myproject. 
# mkproject myproject

virtualenvwrapper provides tab-completion on environment names. It really helps when you have a lot of environments and have trouble remembering their names. 

workon also deactivates whatever environment you are currently in, so you can quickly switch between environments. 

3. Deactivating is still the same: 
# deactivate


4. To delete: 
# rmvirtualenv venv


Other useful commands 
* lsvirtualenv: List all of the environments.
* cdvirtualenv: Navigate into the directory of the currently activated virtual environment, so you can browse its site-packages, for example.
* cdsitepackages: Like the above, but directly into site-packages directory.
* lssitepackages: Shows contents of site-packages directory.

Full list of virtualenvwrapper commands. 

virtualenv-burrito 
With virtualenv-burrito, you can have a working virtualenv + virtualenvwrapper environment in a single command. 

autoenv 
When you cd into a directory containing a .env, autoenv automagically activates the environment. Install it: 
# git clone git://github.com/kennethreitz/autoenv.git ~/.autoenv
# echo 'source ~/.autoenv/activate.sh' >> ~/.bashrc


Supplement 
Python 3 Tutorial 第七堂(1)pip 與 venv

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...