1. 概述
最近有个需求,把自己ros工程拆分多个子功能包模块后进行上传;但是功能包的数量太多了,几十个一个个点击太过痛苦,于是找找资料,想到使用catkin_tools、python、pexpect等工具实现了这个功能。
2. 代码
#!/usr/bin/env python
#coding=utf-8
import yaml
import sys, os
import subprocess
import pexpect
def adb_shell(cmd, type=0):
# 执行cmd命令,并等待获取结果
if type == 0:
res = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 使用管道
result = res.stdout.read() # 获取输出结果
res.wait() # 等待命令执行完成
res.stdout.close() # 关闭标准输出
return result
# 不必获取结果,实时执行状态输出
elif type == 1:
res = os.system(cmd)
else:
print("please use true type!")
if __name__ == '__main__':
catkin_list = adb_shell("catkin list")
name_list = yaml.load(catkin_list)
print(name_list)
# 遍历列表并创建git仓库
for packname in name_list:
pack_path = adb_shell("catkin locate " + packname).split("\n")[0]
print(pack_path)
# 1.初始化git仓库
cmd = "cd {0} ; git init {0}; git add -A; git commit -m 'init';".format(pack_path)
ret = adb_shell(cmd)
print(ret)
# 2.上传到gitlab仓库
os.chdir(pack_path) # cd为shell自带的命令,当用which和whereis查找时都会报找不到
# 自动创建远程git仓库
child = pexpect.spawn("git push --set-upstream https://gitlab.example.com/namespace/{}.git master".format(packname))
child.logfile_read = sys.stdout
child.expect("Username for") # 匹配这一行的账户提示符,然后输入下一行的账户字符
child.sendline("xxxxx@qq.com") # 输入账户
child.expect("Password for") # 匹配这一行的密码提示符,然后输入下一行的密码字符
child.sendline("xxxxx") # 输入密码
child.expect(pexpect.EOF) # 结束符,正常结束这一次输入