[英]How to run several scripts in differents folders on Python
如果你想通过一组目录进行递归,我推荐使用 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)
编辑:添加了使用 import library+exec_module 来运行 python 文件。 从这里引用的导入方法。
Popen
需要参数列表,那么呢?
import subprocess
from subprocess import Popen
Popen(['python', 'p1/P1_T1.py'])
time.sleep(1)
Popen(['python','p2/P2_T1.py'])
这对你有用吗? 有很好的教程 - Python 3 Subprocess Examples
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.