首發(fā)于微信公眾號東哥夜談。歡迎關(guān)注東哥夜談,讓我們一起聊聊個人成長、投資、編程、電影、運動等話題。
本帳號所有文章均為原創(chuàng)。文章可以隨意轉(zhuǎn)載,但請務(wù)必注明作者。如果覺得文章有用,歡迎轉(zhuǎn)發(fā)朋友圈分享。
1. 緣起
每次給 Gitpage 推送的時候都挺繁瑣的。先啟動終端、切換到目標目錄,然后git add .
,然后git commit -m "something"
,然后git push origin master
,等完事后還得退出。于是琢磨著怎么用 Python 來簡化這一流程。
2. 思路
Git 命令本質(zhì)上是在命令行里面輸入一些 git 命令,所以只要我們能在 Python 里面模擬 Shell 環(huán)境輸入命令即可。在《怎樣在 Python 中調(diào)用系統(tǒng)程序打開文件》里面我們提到可以用subprocess.call(["open", "about.html"])
。今天為了寫這篇文章,本著嚴謹一點的態(tài)度又去翻看了一下文檔,結(jié)果發(fā)現(xiàn)這個操作現(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
一般來說推薦用run()
,更高級的可以用Popen()
。好吧,那就用run()
吧。run()
的參數(shù)可以為兩類,一種是 str,包含所有命令和參數(shù),另一種是列表,即把所有命令及相關(guān)參數(shù)按列表的方式提供。Python 文檔建議采用列表,那就按它推薦的方法來吧。
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).
那下一步問題就簡單了。
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.**********')
運行該腳本,即可自動化執(zhí)行推送,Oh yeah。
4. 延伸
今天我們通過討論如何用 Python 執(zhí)行 git 命令,研究了如何調(diào)用 Python 執(zhí)行系統(tǒng) shell 的一些命令。這樣就可以充分利用 shell 本身很有優(yōu)勢的地方,畢竟不管是 Mac 還是 Windows,原生的 shell 有些時候的確更為簡單好用一些。
借著這個腳本,我把之前的一些文章統(tǒng)計了出來,統(tǒng)一放到了一個新建的 Python 頁面下,算是給自己開啟了一個 Python 專欄,專門用來記錄學習 Python 過程中的一些問題與思考。更新腳本就在這個推送腳本上修改,所以每次推送自動更新頁面目錄。歡迎大家圍觀哈。
終于能用 Python 做點實際的東西了,呵,這種感覺真好 O(∩_∩)O
5. 來源
