gpt4 book ai didi

python - 用于从文件中选择单个 Python 函数的 Bash 脚本

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:05 26 4
gpt4 key购买 nike

对于 git alias problem ,我希望能够按名称从文件中选择一个 Python 函数。例如:

  ...
def notyet():
wait for it

def ok_start(x):
stuff
stuff
def dontgettrickednow():
keep going
#stuff
more stuff

def ok_stop_now():

在算法方面,以下内容足够接近:

  1. 当找到匹配 /^(\s*)def $1[^a-zA-Z0-9]/ 的行时开始过滤>
  2. 继续匹配,直到找到不是 ^\s*#^/\1\s] 的行(即, 一个可能缩进的评论,或者比前一个缩进更长的缩进)

(我真的不在乎是否拾取了以下函数之前的装饰器。结果是供人类阅读的。)

我试图用 Awk(我几乎不知道)来做到这一点,但它比我想象的要难一些。对于初学者,我需要一种方法来存储原始 def 之前的缩进长度。

最佳答案

使用 awk 的一种方式。代码有很好的注释,所以我希望它很容易理解。

infile 的内容:

  ...
def notyet():
wait for it

def ok_start(x):
stuff
stuff
def dontgettrickednow():
keep going
#stuff
more stuff

def ok_stop_now():

script.awk 的内容:

BEGIN {
## 'f' variable is the function to search, set a regexp with it.
f_regex = "^" f "[^a-zA-Z0-9]"

## When set, print line. Otherwise omit line.
## It is set when found the function searched.
## It is unset when found any character different from '#' with less
## spaces before it.
in_func = 0
}

## Found function.
$1 == "def" && $2 ~ f_regex {

## Get position of first 'd' in the line.
i = index( $0, "d" )

## Sanity check. Never should success because the condition was
## checked before.
if ( i == 0 ) {
next
}

## Get characters until matched index before, check that all of
## them are spaces, and get its length.
indent = substr( $0, 0, i - 1 )
if ( indent ~ /^[[:space:]]*$/ ) {
num_spaces = length( indent )
}

## Set variable, print line and read next one.
in_func = 1
print
next
}

## When we are inside the function, line doesn't begin with '#' and
## it's not a blank line (only spaces).
in_func == 1 && $1 ~ /^[^#]/ && $0 ~ /[^[:space:]]/ {

## Get how many characters there are until first non-space. The result
## is the position of first non-blank, so substract one to get the number
## of spaces.
spaces = match( $0, /[^[:space:]]/ )
spaces -= 1

## If current indent is less or equal that the indent of function definition, then
## end of function found, so end processing.
if ( spaces <= num_spaces ) {
in_func = 0
}
}

## Self-explanatory.
in_func == 1 {
print
}

像这样运行它:

awk -f script.awk -v f="ok_start" infile

输出如下:

  def ok_start(x):
stuff
stuff
def dontgettrickednow():
keep going
#stuff
more stuff

关于python - 用于从文件中选择单个 Python 函数的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10512351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com