Home>
Contents

I want to run multiple Pythons in parallel at the same time using PowerShell.
Start-JobI used, but the situation is that they are running in series instead of in parallel.
I haven't found the cause even after investigating, so I'd like to ask for advice.

Execution flow
  1. From PowerSell. \ Execute.ps1Run
  2. Execute.ps1 in the backgroundBefore.pyRun
  3. Execute.ps1 in the backgroundAfter.pyRun
# File name: Execute.ps1
$py_before = {py -3 Before.py}
$py_after = {py -3 After.py}
#Background execution
Start-Job -Name "py_before" $py_before
Start-Job -Name "py_after" $py_after
#Wait for the end of background Job
Get-Job -name "py_ *" | Wait-Job | Receive-Job
#End of Job
Remove-Job -name "py_ *" -force
#File name: Before.py
import time
for i in range (5):
    print ("before:" + str (i))
    time.sleep (3)
print ("before: finish")
#File name: After.py
import time
for i in range (5):
    print ("after:" + str (i))
    time.sleep (3)
print ("after: finish")
Execution result
before: 0
before: 1
before: 2
before: 3
before: 4
before: finish
after: 0
after: 1
after: 2
after: 3
after: 4
after: finish
Expected execution result

Since we expect it to be executed in parallel, we expect the following output.

before: 0
after: 0
before: 1
after: 1
before: 2
after: 2
before: 3
after: 3
before: 4
after: 4
before: finish
after: finish
  • Answer # 1

    It is only acquired for each job with Receive-Job.
    Try to output the time as follows.

    #File name: Before.py
    import time
    for i in range (5):
        print ("before:" + str (i) + ":" + str (time.time ()))
        time.sleep (3)
    print ("before: finish")

    Output

    before: 0: 1605789093.1365125
    before: 1: 1605789096.1372843
    before: 2: 1605789099.1381838
    before: 3: 1605789102.1381881
    before: 4: 1605789105.1382692
    before: finish
    after: 0: 1605789093.2033725
    after: 1: 1605789096.2043052
    after: 2: 1605789099.2047946
    after: 3: 1605789102.205457
    after: 4: 1605789105.2055109
    after: finish

  • Answer # 2

    In the loopprintIf you display the time with, you can see that it is being executed in parallel.

    The lines are not mixedreceive-jobIs executed in series.