【问题标题】:A bash script that reads python files recursively and stops after the output of each file exists递归读取python文件并在每个文件的输出存在后停止的bash脚本
【发布时间】:2020-09-30 01:12:49
【问题描述】:

我有一个 bash,它递归地读取 *.py 脚本,并在每个 *.py 文件的输出存在于目录(*.pkl 文件)中时停止。 bash 的主要思想是,如果输出不存在,python 脚本必须再次运行,直到为每个 *.py 脚本创建输出。

bash.sh
model1.py
model2.py
model3.py
model1.pkl # expected output
model2.pkl # expected output
model3.pkl # expected output

但是,我在这里有一个问题:当第二个/第三个输出不存在时(来自第二个/第三个 .*py 脚本),bash 没有再次运行(而如果第一个输出不存在,则 bash 再次运行,如应该)。

我的 bash 如下:

#!/bin/bash

for x in $(find . -type f -name "*.py"); do
    if [[ ! -f `basename -s .py $x`.pkl ]]; then #output with the same name of *.py file
        python3 ${x}
    else
        exit 0
    fi
done

那么,如果缺少任何 *.py 脚本的输出,我如何强制 bash 脚本再次运行?还是输出名称有问题?

我尝试使用命令while readuntil,但未能让脚本读取所有*.py 文件。

提前致谢!

【问题讨论】:

    标签: python linux bash for-loop recursion


    【解决方案1】:

    试试这个:不是最好的方法:但至少会帮助你朝着正确的方向前进。

        keep_running(){
    for f in $(find . -type f -name "*.py");
    do
        file_name=$(dirname $f)/$(basename $f .py).pk1
        if [ ! -f "$file_name" ];
        then
            echo "$file_name doesn't exists" # here you can run your python script
        fi
    done
    }
    
    cnt_py=0
    cnt_pkl=1 
    
    while [ $cnt_pkl -ne $cnt_py ] ; do
            keep_running
            cnt_py=`ls -1 *.py| wc -l`
            cnt_pkl=`ls -1 *.pk1| wc -l`
    done
    

    【讨论】:

    • 嗨@change198,感谢您的帮助!是的,现在 bash 工作正常!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2020-06-18
    相关资源
    最近更新 更多