提要
哈喽,大家好!
有没有还在每天都手动打包、部署应用的小伙伴?如果你暂时还切换不到 Jenkins 或 Docker,那可以考虑考虑 Python 哟。
TL;DR
* subprocess:用于执行本地 CMD 命令
* Fabric:用于 SSH 连接远程服务器
* webbrowser:用于打开本地浏览器
持续集成、持续部署,业界已经有很多成熟、可靠的工具可以使用,例如:Jenkins、Docker、GitLab CI/CD、CircleCI、Travis CI等等。
如果你手边恰好有这些专业的工具,而且你恰好也擅长使用这些工具,那很好。
本文提供了一种思路,在你手边没有那些专业工具或者你暂时还不想接触那些专业工具的时候,也能帮你从繁琐的打包、部署工作中解放出来。
Python 就是个很好的选择。
场景1:打包、部署基于 Webpack、React 的前端应用;
每完成一个新功能或每修正一个bug,就需要:
场景2:打包、部署基于 Maven、SpringBoot 的后端应用;
每完成一个后新功能或每修正一个bug,就需要:
上面这两个场景,每天都需要重复进行很多次
emmm...
而且:
某一条命令记不清了...可能需要百度一下...
某一环操作失误了...可能得重新来一次...
远程服务器密码忘了...可能得查查...
...
subprocess 模块允许我们启动一个新进程,并连接到它们的输入/输出/错误管道,从而获取返回值。
subprocess 模块首先推荐使用的是它的 run 方法,更高级的用法可以直接使用 Popen 接口。
例如:
def npm_build(prj_path):
subprocess.run([r'C:\Program Files\nodejs\npm.cmd', 'run', 'build'], cwd=prj_path)
很显然,我们应该用 Fabric 进行 SSH 操作。
def sftp_upload(local_file_path, remote_file_path):
print('uploading [%s] to [%s] ...' % (local_file_path, remote_file_path))
with fabric.Connection(host=hostname, user=username, connect_kwargs={'password': password}) as c:
c.put(local_file_path, remote_file_path)
print('done.')
def ssh_exec(cwd, cmd):
with fabric.Connection(host=hostname, user=username, connect_kwargs={'password': password}) as c:
with c.cd(cwd):
r = c.run(cmd, encoding='utf-8')
print(r)
webbrowser 模块提供了一系列接口,用于控制用户的默认浏览器,以及调用系统默认浏览器打开网页或文件。
API:
只需要很简单的封装:
参考:
subprocess — Subprocess management: https://docs.python.org/3/library/subprocess.html#module-subprocess Paramiko: https://github.com/paramiko/paramiko Fabric: https://github.com/fabric/fabric https://docs.fabfile.org/en/stable/ webbrowser: https://docs.python.org/3/library/webbrowser.html?highlight=webbrowser#module-webbrowser