##自動化命令
這一章將會介紹使用python自動執行系統命令,我們將使用python展示兩個執行命令的方式(os,subprocess).
當你開始創建一個腳本的時候,你會發現os.system和subprocess.Popen都是執行系統命令,它們不是一樣的嗎?其實它們兩個根本不一樣,subprocess允許你執行命令直接通過stdout賦值給一個變量,這樣你就可以在結果輸出之前做一些操作,譬如:輸出內容的格式化等.這些東西在你以后的會很有幫助.
Ok,說了這么多,讓我們來看看代碼:
```
>>>
>>> import os
>>> os.system('uname -a')
Linux cell 3.11.0-20-generic #35~precise1-Ubuntu SMP Fri May 2 21:32:55 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
0
>>> os.system('id')
uid=1000(cell) gid=1000(cell) groups=1000(cell),0(root)
0
>>> os.system('ping -c 1 127.0.0.1')
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_req=1 ttl=64 time=0.043 ms
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.043/0.043/0.043/0.000 ms
0
>>>
```
上面這段代碼并沒有完全的演示完os模塊所有的功能,不過你可以使用"dir(os)"命令來查看其他的函數(譯者注: 如果不會使用可以使用help()命令).
下面我們使用subprocess模塊運行相同的命令:
```
>>> import subprocess
>>>
>>> com_str = 'uname -a'
>>> command = subprocess.Popen([com_str], stdout=subprocess.PIPE, shell=True)
>>> (output, error) = command.communicate()
>>> print output
Linux cell 3.11.0-20-generic #35~precise1-Ubuntu SMP Fri May 2 21:32:55 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
>>> com_str = 'id'
>>> command = subprocess.Popen([com_str], stdout=subprocess.PIPE, shell=True)
>>> (output, error) = command.communicate()
>>> print output
uid=1000(cell) gid=1000(cell) groups=1000(cell),0(root)
>>>
```
和第一段代碼對比你會發現語法比較復雜,但是你可以把內容存儲到一個變量里面并且你也可以把返回的內容寫入到一個文件里面去;
```
>>> com_str = 'id'
>>> command = subprocess.Popen([com_str], stdout=subprocess.PIPE, shell=True)
>>> (output, error) = command.communicate()
>>> output
'uid=1000(cell) gid=1000(cell) groups=1000(cell),0(root)\n'
>>> f = open('file.txt', 'w')
>>> f.write(output)
>>> f.close()
>>> for line in open('file.txt', 'r'):
... print line
...
uid=1000(cell) gid=1000(cell) groups=1000(cell),0(root)
>>>
```
這一章我們講解了如何自動化執行系統命令,記住當你以后遇到 CLI的時候可以把它丟到python腳本里面;
最后自己嘗試一下寫一個腳本,把輸出的內容寫入到一個文件里面或者是只輸出部分信息.