提取python文件的代码,并使用bash从中检索值



我有一个setup.py文件,它看起来像这样:

#!/usr/bin/env python
DIR = Path(__file__).parent
README = (DIR / "README.md").read_text()
install_reqs = parse_requirements(DIR / "requirements.txt")
try:
dev_reqs = parse_requirements(DIR / "requirements-dev.txt")
except FileNotFoundError:
dev_reqs = {}
print("INFO: Could not find dev and/or prepro requirements txt file.")

if __name__ == "__main__":
setup(
keywords=[
"demo"
],
python_requires=">=3.7",
install_requires=install_reqs,
extras_require={"dev": dev_reqs},
entry_points={
"console_scripts": ["main=smamesdemo.run.main:main"]
},
)

我想在文件夹中递归地找到这个文件,并提取以下部分:

entry_points={
"console_scripts": ["main=smamesdemo.run.main:main"]
},

也可能看起来像这个

entry_points={"console_scripts": ["main=smamesdemo.run.main:main"]}

DESIRED:我想检查入口点字典是否包含以名称main开头并返回True或False(或抛出错误(的console_scripts部分。

我找到文件和所需的值如下:

grep -rnw "./" -e "entry_points"

这将返回以下内容:

./setup.py:22:        entry_points={

有人知道怎么解决这个问题吗?

假设setup.py文件中只有一个entry_points={...}块具有与您在示例中所述相同的语法。

  • 以下脚本将通过提供请求的输出在当前目录中找到setup.py文件
#!/bin/bash
directory_to_find='.' # Directory path to find the "${py_script}" file.
py_script="setup.py"  # Python script file name.
dictionary_to_match="console_scripts" # Dictionary to match
dictionary_script_to_match="main"      # Script name to match - If the Dictionary found.
########################################################
py_script=$(find "${directory_to_find}" -name "${py_script}" -type f)
found_entrypoint=$(
while IFS='' read -r line ;do
echo -n $line 
done <<< $(fgrep -A1 'entry_points={' ${py_script})
echo -n '}' && echo ""
)
found_entrypoint_dictionary=$(echo ${found_entrypoint} | awk -F'{' '{print $2}' | awk -F':' '{print $1}')
found_entrypoint_dictionary=$(echo ${found_entrypoint_dictionary//"/})
found_dictionary_script=$(echo ${found_entrypoint} | awk -F'[' '{print $2}' | awk -F'=' '{print $1}')
found_dictionary_script=$(echo ${found_dictionary_script//"/})
if ! [[ "${found_entrypoint}" =~ ^entry_points={.* ]] ;then
echo "entry_points not found."
exit 1
fi
if [ "${found_entrypoint_dictionary}" == "${dictionary_to_match}" ] && [ "${found_dictionary_script}" == "${dictionary_script_to_match}" ] ;then
echo "${found_entrypoint}"
echo "True"
elif [ "${found_entrypoint_dictionary}" != "${dictionary_to_match}" ] || [ "${found_dictionary_script}" != "${dictionary_script_to_match}" ] ;then
echo "${found_entrypoint}"
echo "False"
else
echo "Somthing went wrong!"
exit 2
fi
exit 0

最新更新