Python 3.4 Part2

讀檔

f= open("rw_test", "w")         # w代表寫入,w+則是沒有檔案的話會自動新增
f.write("Hello 123")
f.close()

f = open ("rw_test", "r")       # r代表讀取
f.read()

Output: 'Hello 123'

載入模組

範例1:載入模組

import random                   # 載入random模組
print(random.randint(2,29))     # 使用其中的randint函式
from random import randinr      # 載入random的randint模組
print(randint(2,29))            # 使用時不用寫一大串

範例2:讀組網頁

from urllib.request import urlopen          # 載入讀取網頁模組
data = urlopen("http://www.cs.pu.edu.tw/~ylyang/vcs_git.html").read()
str = data.decode()                         # 轉成utf-8格式
print (str)

範例3:寄信功能

import smtplib                              # 載入smtp模組

server = smtplib.SMTP('ms.example.com.tw')   # 設定smtp server
server.set_debuglevel(1)                    # 將寄信每個步驟列出來

server.sendmail('[email protected]', '[email protected]', "HAHAHAHAAAA")   # Mail內容(只寫body部份)
server.quit()
import smtplib                                  # 載入smtp模組
from email.mime.text import MIMEText            # 載入MIMEText模組
from email.header import Header                 # 載入Header模組


msg = MIMEText('嘿嘿嘿嘿嘿','plain','utf-8')    # 設定MIMEText內容,並指令utf-8格式


server = smtplib.SMTP('ms1.example.com.tw')
server.set_debuglevel(1)

server.sendmail('[email protected]', '[email protected]', msg.as_string())
server.quit()

系統操作

範例1:列出目錄中的檔案

import os                           # 載入os模組
cwd = os.getcwd()                   # 取得目前檔案,並存成cwd串列
print ('Current directory is:')
print (os.listdir(cwd))

Output:
Current directory is: ['.ipynb_checkpoints', 'images', 'rw_test', 'py_class_1.ipynb', 'py_class_2.ipynb', 'mydata.pickle', 'python_class_3.ipynb', 'child.py', 'test_mk_dir', 'output']

範例2:列出目錄中的檔案與目錄,及其目錄下的內容(遞迴方式)

import os
for dirname, dirs, files, in os.walk('.'):      # os.walk代表遞迴方式
    print ('dirname: ', dirname+'    dirs: ', dirs,'\nfiles: ', files ,end='\n\n')

Output:

dirname:  .    dirs:  ['.ipynb_checkpoints', 'images', 'test_mk_dir', 'output']
files:  ['rw_test', 'py_class_1.ipynb', 'py_class_2.ipynb', 'mydata.pickle', 'python_class_3.ipynb', 'child.py']
dirname:  ./.ipynb_checkpoints    dirs:  []
files:  ['py_class_1-checkpoint.ipynb', 'py_class_2-checkpoint.ipynb',   'python_class_3-checkpoint.ipynb']
dirname:  ./images    dirs:  []
files:  ['py1.png', 'py3.png', 'py2.png']
dirname:  ./test_mk_dir    dirs:  []
files:  []
dirname:  ./output    dirs:  ['subdir1']
files:  []
dirname:  ./output/subdir1    dirs:  ['subdir2']
files:  []
dirname:  ./output/subdir1/subdir2    dirs:  ['subdir3']
files:  []
dirname:  ./output/subdir1/subdir2/subdir3    dirs:  []
files:  []

範例3:較格式化的顯示

import os
for dirname, dirs, files, in os.walk('.'):
    for f in files:
        print('file', os.path.join(dirname, f))

Output:

file ./rw_test
file ./py_class_1.ipynb
file ./py_class_2.ipynb
file ./mydata.pickle
file ./python_class_3.ipynb
file ./child.py
file ./.ipynb_checkpoints/py_class_1-checkpoint.ipynb
file ./.ipynb_checkpoints/py_class_2-checkpoint.ipynb
file ./.ipynb_checkpoints/python_class_3-checkpoint.ipynb
file ./images/py1.png
file ./images/py3.png
file ./images/py2.png

範例4:刪除檔案

for dirname, dirs, files in os.walk('.'):
    for f in files:
        if f == '.DS_Store':
            path = os.path.join(dirname, f)
            os.remove(path)  #移除檔案

範例5:檢查檔案或目錄是否存在

path = 'output'
if os.path.exists(path):                        # 檢查是否存在
    if os.path.isdir(path):                     # 檢查是否為目錄
        print('{0} is a dir'.format(path))
    else:
        print ('{0} is not a dir.'.format(path))
else:
    print('{0} do not exits!'.format(path))

範例6:新增目錄

path = 'output'
path1 ='test_mk_dir'
os.mkdir(path1)                         # 建立單一目錄
path2 = os.path.join('output', 'subdir1', 'subdir2', 'subdir3')  # 設定階層目錄
os.makedirs(path2)                      # 直接建立樹狀目錄

程序(process)操作

子程序訊息回覆

範例1:subprocess.call()

產生子程序執行指令,若子程序完成會回傳0,有錯誤則回傳大於0的數值。

import subprocess
rc = subprocess.call(["ls","-l"])
print(rc)

Output: 0

範例2:subprocess.check_call()

同subprocess.call()功能,但若回傳值不為0,會顯示錯誤訊息以便Debug用

subprocess.check_call("exit 1", shell=True)

Output:

---------------------------------------------------------------------------
CalledProcessError                        Traceback (most recent call last)
<ipython-input-23-49abebf0c09f> in <module>()
----> 1 subprocess.check_call("exit 1", shell=True)
      2
      3 #shell = True這個參數主要是,python會先再開一個shell出來,並且一整串字串丟給shell來解釋並執行
      4 #基本上有些指令是屬於shell特有的像是 cd <目錄的路徑名稱>就是其中一個例子

/usr/local/lib/python3.4/subprocess.py in check_call(*popenargs, **kwargs)
    559         if cmd is None:
    560             cmd = popenargs[0]
--> 561         raise CalledProcessError(retcode, cmd)
    562     return 0
    563

CalledProcessError: Command 'exit 1' returned non-zero exit status 1

範例3:subprocess.check_output()

將收到子程序執行後的輸出。並如範例2,若回傳值大於0會產生錯誤訊息。

import subprocess
a=subprocess.check_output(["ls", "-a"])
print(a)

Output: b'.\n..\n.ipynb_checkpoints\nchild.py\nimages\nmydata.pickle\noutput\npy_class_1.ipynb\npy_class_2.ipynb\npython_class_3.ipynb\nrw_test\ntest_mk_dir\n'

產生子程序:Popen()

範例1:

import subprocess
child = subprocess.Popen(["ping","-c","5","www.google.com"])  # 產生子程序,讓它ping google5次
print(child.pid)
print("parent process")

範例2:等待子程序完成

import subprocess
child = subprocess.Popen(["ping","-c","5","www.google.com"])
child.wait()
print("parent process")

以下是對於子程序可進行的操作

child.poll()            # 檢查child process狀態
child.kill()            # 終止child process
child.send_signal()     # 向child process發送signal
child.terminate()       # 透過發送terminate(SIGNAL 15)訊號的方式終止child process

標準輸入、輸出、管線

import subprocess
child1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)   # child1的輸出存在stdout中。
child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE)
# wc在unix 系統是一個可以計算行數,byte數以及字數的指令

out = child2.communicate()              # communicate可讀取PIPE中的值。
print(out)

Output: (b' 10 83 573\n', None)

輸入指令讓子程序執行

from subprocess import Popen, PIPE
command1 =input("請輸入shell指令:")             # 讓使用者輸入指令
p = Popen(command1, shell=True ,stdout=PIPE)    # 輸出結果放在stdout中
result = p.stdout.read()
print (result)

Output:
請輸入shell指令:whoami
b'nalant\n'

results matching ""

    No results matching ""