Python脚本如何转换成Bash Shell脚本?

因为实习生老提交一堆乱七八糟的代码,所以决定写个 git hook 禁止提交语法检查不同用过的代码。

初步发现 git 的 hook 机制配合 checkstyle 满足需求,但网上的例子是 python 写的,而 windwos 的 git 运行在 mingw64 环境下,整合起来比较麻烦,开了某软件也下载不不下来那些资源。

跪求懂 python 和 shell 的朋友帮忙转一下。TAT

脚本

https://blog.coderstory.cn/wp-content/uploads/2018/06/pre-commit.txt

代码如下

` #! /usr/bin/env python

-- encoding: utf-8 --

import sys,os,re

print '\n.......................Code Style Checking....................\n'

#the count of level, like ERROR,WARN def get_level(content, level): return len(re.compile(r"[%s]" % level).findall(content))

#get the commit file name (whole path) def get_file_name(content, postfix=None): content = content.replace("\t", " ") line_divided = content.split("\n") space_divided = [[j for j in i.split(" ") if j.strip()]for i in line_divided] filenames = [i[5] for i in space_divided if i] if not postfix: return filenames return [i for i in filenames if ".%s" % postfix in i]

jarpath = os.popen('git config --get checkstyle.jar').read() checkfilepath = os.popen('git config --get checkstyle.checkfile').read()

#check code command command = 'java -jar ' + jarpath[:-1] + ' -c ' + checkfilepath[:-1]

#the file to check files = os.popen('git diff-index --cached HEAD').read()

#the result of command content = get_file_name(files, 'java')

resultsum = 0

for i in content: result = os.popen(command + ' ' + i).read() print result resultsum += get_level(result,'ERROR') resultsum += get_level(result,'WARN')

if resultsum > 0: print '\n.......................You must fix the errors and warnings first, then excute commit command again...........\n' sys.exit(-1) else: print '\n.................................Code is very good...................\n' sys.exit(0) `


Python脚本如何转换成Bash Shell脚本?

20 回复

写一个 CLI 不行嘛。为啥非要转 Bash


这个需求很常见,核心思路是把Python的逻辑用Bash语法重写一遍,没法直接“转换”。我一般这么干:

  1. 拆解Python脚本:先看清楚它干了啥,比如文件操作、调用系统命令、字符串处理、循环判断这些。
  2. 找Bash对应方法
    • 变量和参数:Python的sys.argv对应Bash的$1, $2, $@
    • 条件判断:Python的if-else改成Bash的if [ condition ]; then ... fi
    • 循环for item in list: 改成 for item in list; do ... done
    • 文件读写:Python的open().read()/.write()用Bash的catecho>>>代替。
    • 调用外部命令:Python的subprocess.run()在Bash里直接写命令就行。
    • 字符串处理:这个比较麻烦,Bash原生能力弱,可能得用awksedgrep或者cut来配合。
  3. 注意语法细节:Bash对空格、引号、括号很敏感,变量赋值不能有空格,条件判断括号里必须有空格。
  4. 复杂功能评估:如果原脚本用了requestspandas这些库,那用纯Bash实现会非常困难,可能得考虑装个jq处理JSON,或者干脆保留部分Python代码用python -c来嵌入。

举个例子,一个简单的Python脚本:

import sys
filename = sys.argv[1]
with open(filename, 'r') as f:
    for line in f:
        if 'error' in line.lower():
            print(line.strip())

对应的Bash脚本大概长这样:

#!/bin/bash
filename="$1"
while IFS= read -r line; do
    if echo "$line" | grep -qi "error"; then
        echo "$line"
    fi
done < "$filename"

总结:手动重写,简单脚本可行,复杂脚本得评估。

你听说过 ci 么?

简单你就自己写啊

关键是我都不会啊 TAT

我要的是 commit 的时候 禁止提交 ci 是服务端的 tfs 貌似也不能拒绝吧

cli ? cli 不是命令行么

别人没你的环境,怎么写?
起码也得放字符串的例子,让人知道字符串是什么格式

脚本是 git 自己调用的

git 项目中存在.git 隐藏目录,里面有个 hooks 目录。直接把我提供的脚本去掉扩展名扔到这个 hooks 目录 然后在项目里 git commit 就会自动被 git 调用。hooks 里面也有很多例子

在此谢过

都不知道你那些的命令结果,天知道返回什么内容,不知道内容 怎么写

在脚本开头加 #!/usr/bin/python 即可

shell 语法很简单,楼主看看教程,半天就搞定了
http://www.runoob.com/linux/linux-shell.html

bash 语法大概这样:
-----------------------------------
#!/bin/bash

echo -e ‘\n…Code Style Checking…\n’

#the count of level, like ERROR,WARN
function get_level {
content=$1
level=$2
return grep -o “[$level]” “$content” | wc -l
}

jarpath=$(git config --get checkstyle.jar)
checkfilepath=$(git config --get checkstyle.checkfile)

直接用 wsl 是最简单的办法


~~ LZ 上面说了都不会,意思应该是这个 python 脚本他也看不懂

<br>#!/bin/bash<br><br>echo '.......................Code Style Checking....................'<br><br>git diff-index --cached HEAD |grep '\.java$'|\<br> while read -r FILE_NAME; do<br> java -jar $(git config --get checkstyle.jar) -c $FILE_NAME |tee| grep -Eq '(ERROR|WARN)' &amp;&amp; \<br> echo '.......................You must fix the errors and warnings first, then excute commit command again...........'<br> done<br><br>echo '.................................Code is very good...................'<br>

Not promised to work.

#5
ci 不就是这样么,有改动的时候跑一遍测试,测试不通过就不 merge

Forgetting exit with status

<br>#!/bin/bash<br><br>echo '.......................Code Style Checking....................'<br><br>git diff-index --cached HEAD |grep '\.java$'|\<br> while read -r FILE_NAME; do<br> java -jar $(git config --get checkstyle.jar) -c $FILE_NAME |tee| grep -Eq '(ERROR|WARN)' &amp;&amp; \<br> echo '.......................You must fix the errors and warnings first, then excute commit command again...........' &amp;&amp; \<br> exit -1<br> done<br><br>echo '.................................Code is very good...................'<br>

感谢各位
我现在直接在 maven 中集成 checkstyle 使用 mvn checkstyle:check 调用插件检查代码
根据返回值是 0 还是 1 判断是否通过

gitlab ci 了解一下

谷歌的 fire 了解一下?

回到顶部