国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發(fā)設(shè)計 > 正文

記錄Python處理文件因文件流沒有關(guān)閉而出現(xiàn)的詭異問題

2019-11-14 17:01:44
字體:
供稿:網(wǎng)友

引言

最近在學習Python,每次在新建Python文件時都會在文件的開頭部分加入如下的信息,然后將文件添加可執(zhí)行權(quán)限。自然,這個用程序自動生成最好不過了。所以,一開始就使用了Shell腳本實現(xiàn)一個版本,基本工作正常。今天就想著用Python實現(xiàn)一個對應(yīng)的版本吧,于是乎就開始做了;雖然很簡單的邏輯,很簡單的代碼,不過還是讓我這個新手吃了一點虧。雖然比較曲折,但是還是可以工作了。以下把遇到的問題即解決辦法記錄下來。

#!/usr/bin/env python3# -*-coding: utf-8-*-# author: Chris# blog: http://www.survivalescaperooms.com/chriscabin/# create_time: 2015-09-05 10:01:42'''Add description for this module.'''__author__ = "Christopher Lee"

問題一 Python運行linux shell 命令

主要有以下幾種(將在學習后期做一個系統(tǒng)性的總結(jié)):

  • os.system()
  • os.popen()
  • subPRocess.call()

問題二 為何使用vim打開“創(chuàng)建”后的文件卻并沒有內(nèi)容寫入呢

最初版本的實現(xiàn)代碼示例如下:

def create_py_file():    file_name='demo.py'    # 判斷參數(shù)個數(shù)    args = sys.argv        if len(args) == 2:        file_name = args[1] + '.py'    if len(args) <= 2:        try:            with open(file_name, mode='w') as out_file:                # 向文件中寫入信息                custom_print = partial(print, file=out_file)                custom_print('#!/usr/bin/env python3')                custom_print('# -*-coding: utf-8-*-')                # 此處省略。。。                                # 打開文件                command = 'vim %s +11' % (file_name)                os.system(command)        except Exception as e:            print(e.message)    else:        print("Too many arguments.")if __name__ == '__main__':    create_py_file()

現(xiàn)象說明

  • 本以為在custom_print執(zhí)行后,文件中已經(jīng)寫入相關(guān)信息了,但是在執(zhí)行完vim file_name命令后發(fā)現(xiàn)并沒有內(nèi)容。非常納悶

尋找原因

  • 仔細分析后,才發(fā)現(xiàn)實際上在執(zhí)行打開文件命令時,之前的信息并沒有寫入到新的文件中。因為在with語句塊結(jié)束前,文件流并沒有被關(guān)閉,也就沒有保存到磁盤中,所以才導致問題的發(fā)生。(注意上面的代碼的18、19行,明顯還在with塊中)

解決辦法

  • 其實解決辦法超級簡單,只需要將18、19行代碼往前縮進即可!

最終版本的實現(xiàn)代碼

  • 最終版本的代碼可以完成預(yù)期的要求:可以創(chuàng)建一個新的文件(如果文件存在,則直接打開),向其中添加頭部的信息;最后給文件添加可執(zhí)行權(quán)限,并且使用vim打開。
  • 只需要把文件移動到/usr/local/bin/,并且命名為new即可。這樣,只需要在終端中運行new demo就可以輕松創(chuàng)建一個新的python文件啦!
#!/usr/bin/env python3# -*-coding: utf-8-*-# author: Chris# blog: http://www.survivalescaperooms.com/chriscabin/# create_time: 2015-09-05 10:25:46'''This is a python script, which aims to create a new python file automaticly.'''__author__ = "Christopher Lee"import sysimport timefrom functools import partialimport osdef create_py_file():    file_name = 'demo.py'    # 判斷參數(shù)個數(shù)    args = sys.argv    if len(args) == 2:        file_name = args[1]    if len(args) <= 2:        try:            if os.path.exists(file_name):                print("File exists.")                command = 'vi %s' % file_name                os.system(command)                return None            with open(file_name, mode='w') as out_file:                # 向文件中寫入信息                custom_print = partial(print, file=out_file)                custom_print('#!/usr/bin/env python3')                custom_print('# -*-coding: utf-8-*-')                custom_print('# author: Chris')                custom_print('# blog: http://www.survivalescaperooms.com/chriscabin/')                custom_print('# create_time:', time.strftime('%Y-%m-%d %H:%M:%S'))                custom_print('')                custom_print("'''/nAdd description for this module./n'''")                custom_print('')                custom_print('__author__ = "Christopher Lee"')                custom_print('')            # 當文件流關(guān)閉后再進行操作            # 添加可執(zhí)行權(quán)限            command = 'chmod a+x %s' % file_name            os.system(command)            command = 'vim %s +12' % (file_name)            os.system(command)        except Exception as e:            print(e.message)    else:        print("Too many arguments.")if __name__ == '__main__':    create_py_file()

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 东台市| 赣榆县| 海安县| 威远县| 伊宁县| 三江| 巍山| 万山特区| 衡阳市| 澄城县| 双柏县| 峨眉山市| 石泉县| 会昌县| 北碚区| 开平市| 纳雍县| 怀宁县| 赣州市| 新昌县| 扎兰屯市| 伊金霍洛旗| 莒南县| 临西县| 林甸县| 子长县| 承德县| 新宁县| 义马市| 黎川县| 普格县| 忻城县| 灌南县| 门头沟区| 余姚市| 稻城县| 湖北省| 西城区| 怀柔区| 揭东县| 梨树县|