多次在Windows Shell中运行Python脚本



我想运行以下shell命令10次

./file.py 1111x

'x'范围从0到9

即。每个.file.py文件的不同端口。我需要每个实例以自己的外壳运行。我已经尝试创建一个批处理文件和一个调用Windows Shell但没有成功的Python脚本。

怎么样...

import os
import subprocess 
for x in range(0,10):
    command = './file.py 1111'  + str(x)
    os.system(command)
    #or
    subprocess.call('cmd ' + command, shell=True)

您正在寻找的是PowerShell的工作。您可能需要对此进行一些调整以满足您的特定要求,但这应该做您需要的事情。

[ScriptBlock]$PyBlock = {
   param (
     [int]$x,
     [string]$pyfile
   )
   try {
     [int]$Port = (11110 + $x)
     python $pyfile $Port
   }
   catch {
     Write-Error $_
   }
}
try {
  0..9 | ForEach-Object {
    Start-Job -Name "PyJob $_" -ScriptBlock $PyBlock -ArgumentList @($_, 'path/to/file.py')
  }
  Get-Job | Wait-Job -Timeout <int> 
     #If you do not specify a timeout then it will wait indefinitely. 
     #If you use -Timeout then make sure it's long enough to accommodate the runtime of your script. 
  Get-Job | Receive-Job
}
catch {
  throw $_
}

最新更新