
首發(fā)于微信公眾號(hào)東哥夜談。歡迎關(guān)注東哥夜談,讓我們一起聊聊個(gè)人成長(zhǎng)、投資、編程、電影、運(yùn)動(dòng)等話題。
本帳號(hào)所有文章均為原創(chuàng)。文章可以隨意轉(zhuǎn)載,但請(qǐng)務(wù)必注明作者。如果覺(jué)得文章有用,歡迎轉(zhuǎn)發(fā)朋友圈分享。
1. 緣起
每次給 Gitpage 推送的時(shí)候都挺繁瑣的。先啟動(dòng)終端、切換到目標(biāo)目錄,然后git add .,然后git commit -m "something",然后git push origin master,等完事后還得退出。于是琢磨著怎么用 Python 來(lái)簡(jiǎn)化這一流程。
2. 思路
Git 命令本質(zhì)上是在命令行里面輸入一些 git 命令,所以只要我們能在 Python 里面模擬 Shell 環(huán)境輸入命令即可。在《怎樣在 Python 中調(diào)用系統(tǒng)程序打開(kāi)文件》里面我們提到可以用subprocess.call(["open", "about.html"])。今天為了寫這篇文章,本著嚴(yán)謹(jǐn)一點(diǎn)的態(tài)度又去翻看了一下文檔,結(jié)果發(fā)現(xiàn)這個(gè)操作現(xiàn)在不是推薦操作了:
The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.
17.5. subprocess — Subprocess management — Python 3.6.2 documentation
一般來(lái)說(shuō)推薦用run(),更高級(jí)的可以用Popen()。好吧,那就用run()吧。run()的參數(shù)可以為兩類,一種是 str,包含所有命令和參數(shù),另一種是列表,即把所有命令及相關(guān)參數(shù)按列表的方式提供。Python 文檔建議采用列表,那就按它推薦的方法來(lái)吧。
args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names).
那下一步問(wèn)題就簡(jiǎn)單了。
3. 代碼
date = datetime.datetime.today().isoformat()[0:10]
status = subprocess.run(["git", "status"])
print(status)
print('**********start git add.**********')
gadd = subprocess.run(["git", "add", "."])
print('**********git add done.**********')
print('**********start git commit.**********')
gcom = subprocess.run(["git", "commit", "-m" + date])
print('**********git commit done.**********')
print('**********start git push.**********')
gpush = subprocess.run(["git", "push", "origin", "master"])
print('**********git push done.**********')
運(yùn)行該腳本,即可自動(dòng)化執(zhí)行推送,Oh yeah。
4. 延伸
今天我們通過(guò)討論如何用 Python 執(zhí)行 git 命令,研究了如何調(diào)用 Python 執(zhí)行系統(tǒng) shell 的一些命令。這樣就可以充分利用 shell 本身很有優(yōu)勢(shì)的地方,畢竟不管是 Mac 還是 Windows,原生的 shell 有些時(shí)候的確更為簡(jiǎn)單好用一些。
借著這個(gè)腳本,我把之前的一些文章統(tǒng)計(jì)了出來(lái),統(tǒng)一放到了一個(gè)新建的 Python 頁(yè)面下,算是給自己開(kāi)啟了一個(gè) Python 專欄,專門用來(lái)記錄學(xué)習(xí) Python 過(guò)程中的一些問(wèn)題與思考。更新腳本就在這個(gè)推送腳本上修改,所以每次推送自動(dòng)更新頁(yè)面目錄。歡迎大家圍觀哈。
終于能用 Python 做點(diǎn)實(shí)際的東西了,呵,這種感覺(jué)真好 O(∩_∩)O
5. 來(lái)源