运行一个folder/directory整体在Python

Running a folder/directory as a whole in Python

我可以 运行 一个 Python 文件夹或目录作为一个整体来执行其中的所有 .py 文件吗?
编辑:我正在使用 Windows Powershell。

对于 bash,此问题已在 Run all Python files in a directory

得到解答

你可以运行:

for f in *.py; do python "$f"; done

如果您使用 Powershell,您可以使用:

Get-Childitem -Path c:\path\to\scripts -Filter *.py | % {python $_.FullName}

EDIT:正如 Duncan 所说,这是 Powershell 上的较短解决方案:

ls C:\path\to\scripts\*.py | %{ python $_.Fullname}

试试这个:

import os
path = 'path\to\your\directory\'
files = os.listdir (path)
for i in files:
    if i.endswith('.py'):
        os.system("python "+path+i)

在 Powershell 中您可以使用:

Get-Childitem -Path c:\to\folder\ -Filter *.py | % {& $_.FullName}