【问题标题】:Running a folder/directory as a whole in Python在 Python 中作为一个整体运行文件夹/目录
【发布时间】:2015-09-23 05:58:38
【问题描述】:

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

【问题讨论】:

  • 您的意思是在特定文件夹中运行所有.py 脚本?一个接一个?
  • 如果你会使用 bash,你可以试试ls *.py | while read line ; do python $line <optionally specify some arguments> ; done
  • 在不同的进程中还是全部在同一个进程中?

标签: python powershell directory


【解决方案1】:

bashRun 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:就像邓肯说的,这是Powershell上的一个更短的解决方案:

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

【讨论】:

  • 我确实看到了这个问题,但是我使用的是 Windows Powershell。
  • @always_confused,请在问题中提及您使用的是 Powershell/cmd 或将其添加为标签。
  • 如果写一个脚本,我会写出完整的Get-ChildItem,但如果这是交互完成的,那么只写ls *.py | % { python $_.FullName }会更短
【解决方案2】:

试试这个:

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

【讨论】:

    【解决方案3】:

    在 Powershell 中你可以使用:

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

    【讨论】:

      猜你喜欢
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 2016-08-20
      • 2013-05-03
      • 1970-01-01
      • 2015-11-28
      相关资源
      最近更新 更多