gpt4 book ai didi

python - 如何在Python上运行不同文件夹中的多个脚本

转载 作者:行者123 更新时间:2023-12-01 07:16:00 27 4
gpt4 key购买 nike

我必须为纸张运行很多脚本,并且我希望使其自动化。我有几个文件夹(P1,P2,...,PN),其中有一个脚本(test1,test2,... testN),我需要运行所有这些,但是我自己一个人做,我浪费了很多我没有时间!

enter image description here

enter image description here

我尝试了子进程:

enter image description here

其中 P1_T1 是:

for i in range(5):
x = i+2*i

print(x)

P1_T2 是:

for i in range(5):
x = i+3*i
print(x)

但是没有成功。

最佳答案

如果您想递归访问一组目录,我建议使用 os.walk。此实现应尝试在根目录中的每个文件上运行 POpen 'python [filename]':

import os
import importlib.util


path = "C:\\SO\\testfolder" # <--- replace this with the path to the folder containing all of your p1, p2, p3, p4 folders.

for root, subdirs, files in os.walk(path):
for file in files:
file_path = os.path.join(root, file)
filename, file_extension = os.path.splitext(file_path)
if file_extension == ".py":
print("Now Executing: " + filename + "-----------")
spec = importlib.util.spec_from_file_location(file, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

编辑:添加使用导入库+exec_module来运行python文件。导入方法引用here .

关于python - 如何在Python上运行不同文件夹中的多个脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57945617/

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