<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                [TOC] * * * * * > * 模塊的分類 > 1. python內置模塊(標準庫) > 2. 開源模塊 > 3. 自定義模塊 > ## 1. shelve模塊 在python3中我們使用json或者pickle持久化數據,能dump多次,但只能load一次,因為先前的數據已經被后面dump的數據覆蓋掉了。如果我們想要實現dump和load多次,可以使用shelve模塊。shelve模塊可以持久化所有pickle所支持的數據類型。類似于鍵值對的文件序列化 1. 寫入數據(打開文件,寫入鍵值,關閉文件) ~~~ import shelve import datetime d = shelve.open('shave.txt') info = {"age":25,"name":'dailin'} name = ['alex','rain','peter'] d['info'] = info d['name'] = name date = datetime.datetime.now() d['date'] = date d.close() ~~~ 2. 讀數據(打開文件,獲取鍵對應的值,關閉文件) ~~~ import shelve d = shelve.open('shave.txt') print(d.get('info')) d.close() ~~~ ## 2. os * 文件與路徑的操作 在自動化測試中,經常需要查找操作文件,比如說查找配置文件(從而讀取配置文件的信息),查找測試報告(從而發送測試報告郵件),經常要對大量文件和大量路徑進行操作,這就依賴于os模塊,所以今天整理下比較常用的幾個方法。網上這方面資料也很多,每次整理,只是對自己所學的知識進行梳理,從而加深對某個模塊的使用。 #### 2.1 當前路徑及路徑下的文件 * os.getcwd(): 查看當前所在路徑。 * os.listdir(path): 列舉目錄下的所有文件。返回的是列表類型。 ~~~ >>> import os >>> os.getcwd() 'D:\\pythontest\\ostest' >>> os.listdir(os.getcwd()) ['hello.py', 'test.txt'] ~~~ #### 2.2 絕對路徑 * os.path.abspath(path):返回path的絕對路徑。 ~~~ # 獲取當前絕對路徑 . >>> os.path.abspath('.') 'D:\\pythontest\\ostest' # 獲取當前路徑上一級絕對路徑 .. >>> os.path.abspath('..') 'D:\\pythontest' ~~~ #### 2.3 查看路徑的文件夾部分和文件名部分 * os.path.split(path): 將路徑分解為(文件夾,文件名),返回的是元組類型。可以看出,若路徑字符串最后一個字符是\,則只有文件夾部分有值;若路徑字符串中均無\,則只有文件名部分有值。若路徑字符串有\,且不在最后,則文件夾和文件名均有值。且返回的文件夾的結果不包含\. * os.path.join(path1,path2,...):將path進行組合,若其中有絕對路徑,則之前的path將被刪除。 ~~~ # 切分路徑與文件 >>> os.path.split('D:\\pythontest\\ostest\\Hello.py') ('D:\\pythontest\\ostest', 'Hello.py') >>> os.path.split('.') ('', '.') >>> os.path.split('D:\\pythontest\\ostest\\') ('D:\\pythontest\\ostest', '') >>> os.path.split('D:\\pythontest\\ostest') ('D:\\pythontest', 'ostest') >>> os.path.join('D:\\pythontest', 'ostest') 'D:\\pythontest\\ostest' # 路徑與文件拼接 >>> os.path.join('D:\\pythontest\\ostest', 'hello.py') 'D:\\pythontest\\ostest\\hello.py' # 絕對路徑與絕對路徑拼接,前邊的被覆蓋 >>> os.path.join('D:\\pythontest\\b', 'D:\\pythontest\\a') 'D:\\pythontest\\a' ~~~ * os.path.dirname(path):返回path中的文件夾部分,結果不包含'\' ~~~ >>> os.path.dirname('D:\\pythontest\\ostest\\hello.py') 'D:\\pythontest\\ostest' >>> os.path.dirname('.') '' >>> os.path.dirname('D:\\pythontest\\ostest\\') 'D:\\pythontest\\ostest' >>> os.path.dirname('D:\\pythontest\\ostest') 'D:\\pythontest' ~~~ * os.path.basename(path):返回path中的文件名。 ~~~ >>> os.path.basename('D:\\pythontest\\ostest\\hello.py') 'hello.py' >>> os.path.basename('.') '.' >>> os.path.basename('D:\\pythontest\\ostest\\') '' >>> os.path.basename('D:\\pythontest\\ostest') 'ostest' ~~~ #### 2.4 查看文件時間 * os.path.getmtime(path): 文件或文件夾的最后修改時間,從新紀元到訪問時的秒數。 * os.path.getatime(path): 文件或文件夾的最后訪問時間,從新紀元到訪問時的秒數。 * os.path.getctime(path): 文件或文件夾的創建時間,從新紀元到訪問時的秒數。 ~~~ >>> os.path.getmtime('D:\\pythontest\\ostest\\hello.py') 1481695651.857048 >>> os.path.getatime('D:\\pythontest\\ostest\\hello.py') 1481687717.8506615 >>> os.path.getctime('D:\\pythontest\\ostest\\hello.py') 1481687717.8506615 ~~~ #### 2.5 查看文件大小 * os.path.getsize(path): 文件或文件夾的大小,若是文件夾返回0。 ~~~ >>> os.path.getsize('D:\\pythontest\\ostest\\hello.py') 58L >>> os.path.getsize('D:\\pythontest\\ostest') 0L ~~~ #### 2.6 查看文件是否存在 * os.path.exists(path): 文件或文件夾是否存在,返回True 或 False。 ~~~ >>> os.listdir(os.getcwd()) ['hello.py', 'test.txt'] >>> os.path.exists('D:\\pythontest\\ostest\\hello.py') True >>> os.path.exists('D:\\pythontest\\ostest\\Hello.py') True >>> os.path.exists('D:\\pythontest\\ostest\\Hello1.py') False ~~~ #### 2.7 一些表現形式參數 os中定義了一組文件、路徑在不同操作系統中的表現形式參數,如: ~~~ >>> os.sep # 系統路徑分隔符 '\\' >>> os.extsep '.' >>> os.pathsep # 輸出用于分割文件路徑的字符串 ';' >>> os.linesep # 獲取系統換行符 '\r\n' ~~~ #### 2.8 實例說明 在自動化測試過程中,常常需要發送郵件,將最新的測試報告文檔發送給相關人員查看,這是就需要查找最新文件的功能。 舉例:查找文件夾下最新的文件。 ~~~ import os def new_file(test_dir): #列舉test_dir目錄下的所有文件(名),結果以列表形式返回。 lists=os.listdir(test_dir) #sort按key的關鍵字進行升序排序,lambda的入參fn為lists列表的元素,獲取文件的最后修改時間,所以最終以文件時間從小到大排序 #最后對lists元素,按文件修改時間大小從小到大排序。 lists.sort(key=lambda fn:os.path.getmtime(test_dir+'\\'+fn)) #獲取最新文件的絕對路徑,列表中最后一個值,文件夾+文件名 file_path=os.path.join(test_dir,lists[-1]) return file_path #返回D:\pythontest\ostest下面最新的文件 print new_file('D:\\system files\\workspace\\selenium\\email126pro\\email126\\report') ~~~ ~~~ # 關于lambda的用法(python中單行的最小函數): key=lambda fn:os.path.getmtime(test_dir+'\\'+fn) #相當于 def key(fn): return os.path.getmtime(test_dir+'\\'+fn) ~~~ #### 2.9 遍歷文件 os.walk(top, topdown=True, onerror=None, followlinks=False) 可以得到許多個三元tupple(dirpath, dirnames, filenames), 即每個文件夾的(文件夾,文件夾所有子文件夾列表,文件夾下的所有文件列表) dirpath 是一個string,代表目錄的路徑, dirnames 是一個list,包含了dirpath下所有子目錄的名字。 filenames 是一個list,包含了非目錄文件的名字。 這些名字不包含路徑信息,如果需要得到全路徑,需要使用os.path.join(dirpath, name). 循環遍歷work目錄下的文件 ~~~ for dirpath, dirnames, filenames in os.walk('C:\\Users\\Administrator\\Desktop\\work'): for file in filenames: fullpath = os.path.join(dirpath, file) print(fullpath) ~~~ ~~~ # 根目錄 # 根目錄下的子目錄 # 根目錄下的文件 ('C:\\Users\\Administrator\\Desktop\\work', ['fastdfsClient', 'PythonRedis'], ['daily.txt', 'daily.txt.bak', 'fastdfsClient.rar', ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient', ['.idea', '.settings', 'bin', 'lib', 'src'], ['.classpath', '.project', 'fastdfsClient.iml']) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\.idea', ['libraries'], ['misc.xml', 'modules.xml', 'workspace.xml']) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\.idea\\libraries', [], ['jdk1_8.xml']) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\.settings', [], ['org.eclipse.jdt.core.prefs']) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\bin', ['cn'], []) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\bin\\cn', ['itcast'], []) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\bin\\cn\\itcast', ['fastdfs'], []) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\bin\\cn\\itcast\\fastdfs', ['cliennt'], []) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\bin\\cn\\itcast\\fastdfs\\cliennt', [], ['FastdfsClientTest.class', 'fdfs_client.conf']) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\lib', [], ['fastdfs_client_v1.20.jar', 'junit-4.9.jar', 'lib.lnk']) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\src', ['cn'], []) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\src\\cn', ['itcast'], []) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\src\\cn\\itcast', ['fastdfs'], []) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\src\\cn\\itcast\\fastdfs', ['cliennt'], []) ('C:\\Users\\Administrator\\Desktop\\work\\fastdfsClient\\src\\cn\\itcast\\fastdfs\\cliennt', [], ['FastdfsClientTest.java', 'fdfs_client.conf']) ('C:\\Users\\Administrator\\Desktop\\work\\PythonRedis', ['.idea', '__pycache__'], ['client.conf', 'config$py.class', 'config.py', 'PythonFdfsRedis.py', 'test.py']) ('C:\\Users\\Administrator\\Desktop\\work\\PythonRedis\\.idea', ['inspectionProfiles'], ['misc.xml', 'modules.xml', 'PythonRedis.iml', 'workspace.xml']) ('C:\\Users\\Administrator\\Desktop\\work\\PythonRedis\\.idea\\inspectionProfiles', [], []) ('C:\\Users\\Administrator\\Desktop\\work\\PythonRedis\\__pycache__', [], ['config.cpython-36.pyc']) ~~~ ### 2.10 os.environ 用戶獲取系統信息 ~~~ os.environ.keys() 主目錄下所有的key os.environ['HOMEPATH']:當前用戶主目錄。 ~~~ ## 3. sys sys模塊提供了一系列有關Python運行環境的變量和函數。 * sys.argv 可以用sys.argv獲取當前正在執行的命令行參數的參數列表(list)。 ~~~ 變量 解釋 sys.argv[0] 當前程序名 sys.argv[1] 第一個參數 sys.argv[0] 第二個參數 ~~~ ~~~ # encoding: utf-8 # filename: argv_test.py import sys # 獲取腳本名字 print 'The name of this program is: %s' %(sys.argv[0]) # 獲取參數列表 print 'The command line arguments are:' for i in sys.argv: print i # 統計參數個數 print 'There are %s arguments.'%(len(sys.argv)-1) ~~~ * sys.platform 獲取當前執行環境的平臺,如win32表示是Windows 32bit操作系統,linux2表示是linux平臺; * sys.path path是一個目錄列表,供Python從中查找第三方擴展模塊。在python啟動時,sys.path根據內建規則、PYTHONPATH變量進 ## 4. xml ~~~ <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year updated_by="Alex" updated_by_tuna="yes">2010</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year updated_by="Alex" updated_by_tuna="yes">2013</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> </country> <country name="Panama"> <rank updated="yes">69</rank> <year updated_by="Alex" updated_by_tuna="yes">2013</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> <info> <population>8</population> <size>960</size> </info> </country> </data> ~~~ #### 4.1 查找 ~~~ import xml.etree.ElementTree as etree # 解析樹 parsedTree = etree.parse('xmltest.xml') root = parsedTree.getroot() for child in root: print(child.tag,child.attrib) for node in child: print(node.tag,node.text) # 獲取year標簽的迭代器 for node in root.iter('year'): print(node.tag, node.text) ~~~ #### 4.2 修改 ~~~ __author__ = 'dailin' import xml.etree.ElementTree as etree tree = etree.parse('xmltest.xml') root = tree.getroot() # 獲取year標簽的迭代器 for node in root.iter('year'): new_year = int(node.text)+1 node.text = str(new_year) node.set('updated_by_tuna','yes') # 加屬性 tree.write('xmltest.xml') # 寫回去 # 刪除 for country in root.findall('country'): rank = int(country.find('rank').text) if rank > 50: root.remove(country) tree.write('output.xml') ~~~ #### 4.3 創建 ~~~ __author__ = 'dailin' import xml.etree.ElementTree as etree new_xml = etree.Element("personinfolist") # 根節點 # 給new_xml 添加子節點personinfo personinfo = etree.SubElement(new_xml, "personinfo", attrib={"enrolled": "yes"}) # 給personinfo節點添加子節點name name = etree.SubElement(personinfo, "name") name.text = "Alex Li" # name節點文本 age = etree.SubElement(personinfo, "age", attrib={"checked": "no"}) age.text = '56' sex = etree.SubElement(personinfo, "sex") sex.text='women' personinfo2 = etree.SubElement(new_xml, "personinfo", attrib={"enrolled": "no"}) name = etree.SubElement(personinfo2, "name") name.text = "Oldboy Ran" age = etree.SubElement(personinfo2, "age") age.text = '19' et = etree.ElementTree(new_xml) # 生成文檔對象xml_declaration=True xml聲明 et.write("createdByTuna.xml", encoding="utf-8", xml_declaration=True) ~~~ 得到 ~~~ <?xml version='1.0' encoding='utf-8'?> <personinfolist> <personinfo enrolled="yes"> <name>Alex Li</name> <age checked="no">56</age> <sex>women</sex> </personinfo> <personinfo enrolled="no"> <name>Oldboy Ran</name> <age>19</age> </personinfo> </personinfolist> ~~~ ## 5. ConfigParser 一,首先說說 所謂 ini 文件以及 ini的文件格式: ini 文件其實就是所謂的初始化配置文件,一般的格式為: ~~~ [SECTION0] # 相當于一個配置分類 key0 = value0 # 配置項 key1 = value1 [SECTION1] key0 = value0 key1 = value1 ~~~ * 如 ~~~ [config] --oltp-tables-count=10 --oltp-table-size=100000 --num-threads=8 --max-time=600 ~~~ 二,configparser包 > ConfigParser包是創建一個管理對象,再把配置文件read進去,做了其他操作后,再以打開方式打開文件,寫回文件里。(注意!是以打開方式!打開方式!不是追加方式!) > 因為它本身的機制就是會先把文件復制一份,進行操作后,再整個文件內容寫回文件里的。 > 三,相關操作:(一個 item 由 KEY和VALUE組成) > cfg = configparser.ConfigParser() > 創建一個管理對象 cfg > cfg.read(file_path) > 把一個 ini文件讀到cfg中 > se_list = cfg.sections() > #用一個list存放ini文件中的所有 SECTIONS > item = cfg.items(SECTION) > #用一個列表item存放一個SECTION中的所有items(KEY--VALUE) > cfg.remove_option(se,key) > #刪除一個SECTION中的一個item(以鍵值KEY為標識) > cfg.remove_section(se) > #刪除一個SECTION > cfg.add_section(se) > #增加一個SECTION > cfg.set(se,key,value) > #往一個SECTION中增加一個 item(KEY--VALUE) > cfg.wrtie(fp) > #往文件描述符指向的文件中寫入修改后的內容 # -*- codeding: utf-8 -*- import sys import os import configparser #導入 configparser包 class client_info(object): def __init__(self,file): self.file = file self.cfg = configparser.ConfigParser() #創建一個管理對象。 def cfg_load(self): self.cfg.read(self.file) #把文件導入管理對象中,把文件內容load到內存中 def cfg_dump(self): se_list = self.cfg.sections() #cfg.sections()顯示文件中的所有 section print('==================>') for se in se_list: print(se) print(self.cfg.items(se)) print('==================>') def delete_item(self,se,key): self.cfg.remove_option(se,key) #在section中刪除一個item def delete_section(self,se): self.cfg.remove_section(se) #刪除一個section def add_section(self,se): self.cfg.add_section(se) #添加一個section def set_item(self,se,key,value): self.cfg.set(se,key,value) #往section中添加一個item(一個item由key和value構成) def save(self): fd = open(self.file,'w') self.cfg.write(fd) #在內存中修改的內容寫回文件中,相當于保存 fd.close() if __name__== '__main__': info = client_info('client.ini') info.cfg_load() info.add_section('ZJE') info.set_item('ZJE','name','zhujunwen') info.cfg_dump() info.save() ~~~ import configparser config = configparser.ConfigParser() config.read("ConfigParser.ini") # 獲取配置下的配置值,[config] 代表一個section tableCount = config.get('config','--oltp-tables-count') tableSize = config.get('config','--oltp-table-size') threadNum = config.get('config','--num-threads') maxTime = config.get('config','--max-time') # 獲取配置下的選項 print("table count:" + tableCount) print("table size:" + tableSize) print("thred num:" + threadNum) print("max time:" + maxTime) mysql = config.options("config") print("option:" , mysql) # 獲取section下的所有配置項 item = config.items("config") print("item:",item) ~~~ * 配置文件 ~~~ [config] --oltp-tables-count=10 --oltp-table-size=100000 --num-threads=8 --max-time=600 ~~~ ## 6. hashlib模塊   用于加密相關的操作,3.x里代替了md5模塊和sha模塊,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法 ~~~ import hashlib m = hashlib.md5() m.update(b"Hello") m.update(b"It's me") print(m.digest()) m.update(b"It's been a long time since last time we ...") print(m.digest()) # 2進制格式hash ,用來代表加密后的值 print(len(m.hexdigest())) # 16進制格式hash值,用來代表加密后的值 ''' def digest(self, *args, **kwargs): # real signature unknown """ Return the digest value as a string of binary data. """ pass def hexdigest(self, *args, **kwargs): # real signature unknown """ Return the digest value as a string of hexadecimal digits. """ pass ''' import hashlib # ######## md5 ######## hash = hashlib.md5() hash.update('admin') print(hash.hexdigest()) # ######## sha1 ######## hash = hashlib.sha1() hash.update('admin') print(hash.hexdigest()) # ######## sha256 ######## hash = hashlib.sha256() hash.update('admin') print(hash.hexdigest()) # ######## sha384 ######## hash = hashlib.sha384() hash.update('admin') print(hash.hexdigest()) # ######## sha512 ######## hash = hashlib.sha512() hash.update('admin') print(hash.hexdigest()) ~~~ 還不夠吊?python 還有一個 hmac 模塊,它內部對我們創建 key 和 內容 再進行處理然后再加密 散列消息鑒別碼,簡稱HMAC,是一種基于消息鑒別碼MAC(Message Authentication Code)的鑒別機制。使用HMAC時,消息通訊的雙方,通過驗證消息中加入的鑒別密鑰K來鑒別消息的真偽; 一般用于網絡通信中消息加密,前提是雙方先要約定好key,就像接頭暗號一樣,然后消息發送把用key把消息加密,接收方用key + 消息明文再加密,拿加密后的值 跟 發送者的相對比是否相等,這樣就能驗證消息的真實性,及發送者的合法性了。 ~~~ import hmac h = hmac.new(b'天王蓋地虎', b'寶塔鎮河妖') print h.hexdigest() ~~~ ## 7. subprocess模塊 subprocess模塊是python從2.4版本開始引入的模塊。主要用來取代 一些舊的模塊方法,如os.system、os.spawn*、os.popen*、commands.*等。subprocess通過子進程來執行外部指令,并通過input/output/error管道,獲取子進程的執行的返回信息。 #### 7.1 subprocess.call(): subprocess.call(命令,shell=Boolean) * 執行命令,并返回執行狀態,且值返回執行狀態,獲取不到命令的執行結果 其中shell參數為False時,命令需要通過列表的方式傳入,當shell為True時,可直接傳入命令 1. subprocess.call():執行命令,并返回執行狀態,其中shell參數為False時,命令需要通過列表的方式傳入,(命令拼接) ~~~ >>> a = subprocess.call(['df','-hT'],shell=False) Filesystem Type Size Used Avail Use% Mounted on udev devtmpfs 486M 4.0K 486M 1% /dev tmpfs tmpfs 100M 520K 99M 1% /run /dev/sda1 ext4 19G 3.3G 15G 19% / none tmpfs 4.0K 0 4.0K 0% /sys/fs/cgroup none tmpfs 5.0M 0 5.0M 0% /run/lock none tmpfs 497M 0 497M 0% /run/shm none tmpfs 100M 0 100M 0% /run/user ~~~ 2. 當shell為True時,可直接傳入命令(用主機原生的shell執行命令) ~~~ >>> a = subprocess.call('ls -l',shell=True) total 160304 drwxrwxr-x 2 tuna tuna 4096 Nov 14 10:06 bzip2-1.0.6 -rw-r--r-- 1 tuna tuna 782025 Jul 31 12:59 bzip2-1.0.6.tar.gz -rw-r--r-- 1 tuna tuna 721128 Sep 13 22:26 libmysqlclient18_5.6.38-1ubuntu14.04_amd64.deb -rw-r--r-- 1 tuna tuna 1028632 Sep 13 22:26 libmysqlclient-dev_5.6.38-1ubuntu14.04_amd64.deb -rw-r--r-- 1 tuna tuna 9458512 Sep 13 22:26 libmysqld-dev_5.6.38-1ubuntu14.04_amd64.deb -rw-r--r-- 1 tuna tuna 12368 Sep 13 22:26 mysql-client_5.6.38-1ubuntu14.04_amd64.deb -rw-r--r-- 1 tuna tuna 25828 Sep 13 22:26 mysql-common_5.6.38-1ubuntu14.04_amd64.deb -rw-r--r-- 1 tuna tuna 322610 Sep 13 22:26 mysql-community-bench_5.6.38-1ubuntu14.04_amd64.deb -rw-r--r-- 1 tuna tuna 5182472 Sep 13 22:26 mysql-community-client_5.6.38-1ubuntu14.04_amd64.deb -rw-r--r-- 1 tuna tuna 10837528 Sep 13 22:26 mysql-community-server_5.6.38-1ubuntu14.04_amd64.deb -rw-r--r-- 1 tuna tuna 30170644 Sep 13 22:26 mysql-community-source_5.6.38-1ubuntu14.04_amd64.deb -rw-r--r-- 1 tuna tuna 14978548 Sep 13 22:26 mysql-community-test_5.6.38-1ubuntu14.04_amd64.deb -rw-r--r-- 1 tuna tuna 12362 Sep 13 22:26 mysql-server_5.6.38-1ubuntu14.04_amd64.deb -rw-r--r-- 1 tuna tuna 72775680 Oct 24 09:29 mysql-server_5.6.38-1ubuntu14.04_amd64.deb-bundle.tar -rw-r--r-- 1 tuna tuna 12368 Sep 13 22:26 mysql-testsuite_5.6.38-1ubuntu14.04_amd64.deb drwxr-xr-x 17 tuna tuna 4096 Nov 14 10:47 php-5.5.35 -rw-rw-r-- 1 tuna tuna 17774228 Apr 28 2016 php-5.5.35.tar.gz drwxrwxr-x 3 tuna tuna 4096 Nov 14 11:27 shell -rw-rw-r-- 1 tuna tuna 5 Nov 15 09:55 test.txt -rw-r--r-- 1 root root 2694 Feb 15 2016 zabbix-release_3.0-1+trusty_all.deb >>> print(a) 0 ~~~ #### 7.2 subprocess.check_call() 用法與subprocess.call()類似,區別是,當返回值不為0時,直接拋出異常 ~~~ >>> a = subprocess.check_call('df -hT',shell=True) Filesystem Type Size Used Avail Use% Mounted on /dev/sda2 ext4 94G 64G 26G 72% / tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm /dev/sda1 ext4 976M 56M 853M 7% /boot >>> print a 0 >>> a = subprocess.check_call('dfdsf',shell=True) /bin/sh: dfdsf: command not found Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/subprocess.py", line 502, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command 'dfdsf' returned non-zero exit status 127 ~~~ ## 7.3 subprocess.check_output(): 用法與上面兩個方法類似,區別是,如果當返回值為0時,直接返回輸出結果,如果返回值不為0,直接拋出異常。需要說明的是,該方法在python3.x中才有。 * 執行命令,并返回結果,注意是返回結果,不是打印,下例結果返回給res ~~~ >>> res=subprocess.check_output(['ls','-l']) >>> res b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n' ~~~ ## 7.4 subprocess.Popen(): run() 在一些復雜場景中,我們需要將一個進程的執行輸出作為另一個進程的輸入。在另一些場景中,我們需要先進入到某個輸入環境,然后再執行一系列的指令等。這個時候我們就需要使用到suprocess的Popen()方法。該方法有以下參數: > args:shell命令,可以是字符串,或者序列類型,如list,tuple。 > bufsize:緩沖區大小,可不用關心 > stdin,stdout,stderr:分別表示程序的標準輸入,標準輸出及標準錯誤 > shell:與上面方法中用法相同 > cwd:用于設置子進程的當前目錄 > env:用于指定子進程的環境變量。如果env=None,則默認從父進程繼承環境變量 > universal_newlines:不同系統的的換行符不同,當該參數設定為true時,則表示使用\n作為換行符 1. 在/root下創建一個suprocesstest的目錄: 在/home/tuna目錄下,創建t3目錄 ~~~ obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/tuna',) ~~~ ~~~ import subprocess # 把標準輸入流、輸出流、錯誤輸出流都交給了subprogress obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # 向輸入流寫東西 obj.stdin.write("print(1)\n") obj.stdin.write("print(2)") obj.stdin.close() # 關閉輸入流 cmd_out = obj.stdout.read() # 讀取輸出流 obj.stdout.close() # 關閉輸出流 cmd_error = obj.stderr.read() # 去取錯誤流 obj.stderr.close() # 關閉錯流 print(cmd_out) # 打印輸出 print(cmd_error) # 打印錯誤輸出 ~~~ * sudo 密碼自動輸入 ~~~ import subprocess def mypass(): mypass = 'tuna' #or get the password from anywhere return mypass echo = subprocess.Popen(['echo',mypass()], stdout=subprocess.PIPE, # 把密碼輸出到了輸出流 ) sudo = subprocess.Popen(''sudo mkdir /home/test, stdin=echo.stdout, # 把密碼給輸入流 stdout=subprocess.PIPE, ) end_of_pipe = sudo.stdout print "Password ok \n Iptables Chains %s" % end_of_pipe.read() ~~~ * 交互 ~~~ import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) obj.stdin.write('print 1 \n ') obj.stdin.write('print 2 \n ') obj.stdin.write('print 3 \n ') obj.stdin.write('print 4 \n ') out_error_list = obj.communicate(timeout=10) # 提交并關閉交互 print out_error_list ~~~
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看