简体   繁体   English

以无限循环和并行方式运行多个 python 脚本(使用 PowerShell)

[英]Running several python scripts in endless loops and in parallel (with PowerShell)

I have seven python scripts that all manipulate some files in my folder system based on some information on an MSSQL server.我有七个 python 脚本,它们都根据 MSSQL 服务器上的一些信息操作我的文件夹系统中的一些文件。 The code is written in a way that a script should just restart whenever it has finished.代码的编写方式是,脚本应该在完成后重新启动。 Additionally, the scripts should run in parallel.此外,脚本应该并行运行。 The order does not matter as long as they are all executed every now and again (that is, it would be bad if Script 1 (reading a file) runs endlessly while Script 7 (deleting all the files that are already read) is never executed. However, it wouldn't matter if Script 1 is run several times before Script 7 is run once).顺序不重要,只要它们都时不时地执行(也就是说,如果脚本 1(读取文件)无休止地运行而脚本 7(删除所有已读取的文件)永远不会执行,那就不好了. 但是,在脚本 7 运行一次之前,脚本 1 是否运行多次也没有关系)。

So far, I've found a solution with PowerShell.到目前为止,我已经找到了 PowerShell 的解决方案。 I have 7 separate PowerShell Scripts (process1.ps1, process2.ps1, ..., process7.ps1) that all look as follows:我有 7 个单独的 PowerShell 脚本(process1.ps1, process2.ps1, ..., process7.ps1) ,它们都如下所示:

while($true)
{
    $i++
    Start-Process -NoNewWindow -Wait python F:\somewhere\something.py
    Start-Sleep -Seconds 10
}

This works if I open 7 different PowerShell consoles and start one .ps1 in each like this:如果我打开 7 个不同的 PowerShell 控制台并像这样在每个控制台中启动一个.ps1 ,这将起作用:

& "F:\PowerShellScripts\process1.ps1"

However, opening and monitoring seven sessions every time is cumbersome.但是,每次打开和监控七个会话很麻烦。 Is there a way to start all these processes in one go but still ensure that they are parallelized correctly?有没有办法一次性启动所有这些进程,但仍然确保它们正确并行化?

You are able to parallelize command in powershell via:您可以通过以下方式在 powershell 中并行化命令:

For easiest use, take jobs (my recommendation for your needs).为了最简单的使用,请选择工作(我根据您的需要推荐)。 For best performance, use runspaces.为获得最佳性能,请使用运行空间。 I have not tried workflows yet.我还没有尝试过工作流。

A starter for jobs:工作入门:

$scriptpaths = "C:\temp\1.py", "C:\temp\2.py"
foreach ($path in $scriptpaths){
    start-job -ScriptBlock {
        Param($path)
        while($true)
        {
            Start-Process -NoNewWindow -Wait python $path
            Start-Sleep -Seconds 10
        }
    } -ArgumentList $path
}

Please do read the documentations though, this code is far from ideal.请务必阅读文档,此代码远非理想。 Also, this code does not synchronize your scripts.此外,此代码不会同步您的脚本。 If one runs faster than the others, they will desynchronize.如果一个运行得比另一个快,它们就会不同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM