最近在學習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"主要有以下幾種(將在學習后期做一個系統(tǒng)性的總結(jié)):
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()custom_print執(zhí)行后,文件中已經(jīng)寫入相關(guān)信息了,但是在執(zhí)行完vim file_name命令后發(fā)現(xiàn)并沒有內(nèi)容。非常納悶with語句塊結(jié)束前,文件流并沒有被關(guān)閉,也就沒有保存到磁盤中,所以才導致問題的發(fā)生。(注意上面的代碼的18、19行,明顯還在with塊中)/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()新聞熱點
疑難解答