python-3.x 如何运行子文件夹中的文件

blmhpbnm  于 2023-01-14  发布在  Python
关注(0)|答案(2)|浏览(176)
import os

root_dir = "D:\extention"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".py"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
                dir_path=(f"Path: ", os.path.join(folder, f))

与此代码我可以找到子文件夹中的py文件,但无法运行该文件
我尝试使用os.system,但出现错误。
我对Python知之甚少,有人能帮助我吗?

cbjzeqam

cbjzeqam1#

你的dir_path是一个元组而不是字符串。省略圆括号。

import os

root_dir = "D:\extention"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".py"):
                print(f"File Name: {f}")
                dir_path=os.path.join(folder, f)
                print(f"Path: {dir_path}")
                os.system(dir_path)
wqnecbli

wqnecbli2#

这将执行dir_path指定的.py文件:

import subprocess

subprocess.run(["python", dir_path])

如果您需要捕获输出,可以使用以下命令:

import subprocess

process = subprocess.Popen(["python", dir_path], stdout=subprocess.PIPE)
output, error = process.communicate()
print(output)

您只需要将其中一个替代方案集成到代码中,如下所示:

import os
import subprocess

root_dir = "D:\extention"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".py"):
                print("File Name: ", f)
                dir_path = os.path.join(folder, f)
                print("Path: ", dir_path)
                subprocess.run(["python", dir_path])

相关问题