专家,我有 50 个 python 脚本,我想在同一个文件夹上一个一个运行。但问题是在我工作的系统中,很多人也经常使用它。所以有可能滥用我的python脚本。所以我想将50个python脚本复制到同一个文件夹,并在运行包含所有内容的主脚本后从同一个文件夹中删除python脚本(script1.py,script2.py...)正在运行的脚本。所以我做了如下所示的事情
#!/bin/sh
python script1.py
python script2.py
python script3.py
python script4.py
python script5.py
python script6.py
python script7.py
python script8.py
python script9.py
python script10.py
....
但在上面的脚本问题是,如果我删除python脚本,只有第一个python脚本,即python script1.py
正在运行而不是其他脚本。我希望专家能帮助我克服这个问题。
答案 0 :(得分:1)
你做错了。
您应该编写一个 main.py 程序,它将一个接一个地执行您的功能。
在您当前使用的方式中,当 cli 传递给 script1.py 时,仅执行第一个,如果您的脚本不退出,其他将被忽略。
例如,如果您犯了一个无限循环错误,那么其他人将永远不会运行。
我建议学习 python 导入和执行。
一种方法是:
# main.py you have the script1.py and others in same folder.
# you need to have the scripts inside of the functions so you could as well do that in same file.
# so script1 should look like:
def script1_func(): # any arguments that are needed can be passed
# code of your script here
return value # if your script returns some value write it there
# then in main.py
import script1
import script2
import script3
if __name__ == '__main__':
script1.script1_func()
script2.script2_func()
script3.script3_func()
# on that way you can execute them all in sequence. If needed to use paralelism check multithreading.
# if you need to remove them or any other files.
import os
basedir = os.path.abspath(os.path.dirname(__file__))
# this will give you a path to the file and then you just issue delete
if os.path.exists(basedir + "script1.py"):
os.remove(basedir + "script1.py")
else:
print("The file does not exist")
os.rmdir(basedir) # this will delete whole folder
顺便说一句,最好使用更好的约定,不要重复类似的功能。
https://gist.github.com/MarkoShiva/7584151b08a095a1708bdee339f61a65
执行相同操作的其他方法是对来自 bash 的每个文件运行 exec,如果脚本比内核多,这可能会导致机器负载过多。
那是另一个答案。 所以其他用户建议你使用 find 命令并行执行脚本。
答案 1 :(得分:0)
对于您的确切需求,您可以使用以下解决方案
我创建了 2 个示例 Python 文件和一个 shell 脚本来调用这两个脚本。
➜ 65976750 ls
sandex.sh script1.py script2.py
➜ 65976750 bash -x sandex.sh
+ mkdir ./sandexec
+ find . -name '*.py' -exec cp '{}' ./sandexec ';'
+ python3 ./sandexec/script1.py
running python script 1
+ python3 ./sandexec/script2.py
Running from script2
+ rm -rf ./sandexec
➜ 65976750 cat sandex.sh
mkdir ./sandexec
find . -name "*.py" -exec cp {} ./sandexec \;
python3 ./sandexec/script1.py
python3 ./sandexec/script2.py
rm -rf "./sandexec"
➜ 65976750 ls
sandex.sh script1.py script2.py
➜ 65976750