Python popen wait command not behaving as expected
<p>I've a powershell script which calls an API and returns 0 or 99 based on if the POST request went through. My powershell code:</p>

<pre><code>try
{
    Invoke-RestMethod -uri $url -Method Post -Body $body -ContentType 'application/json' -ErrorAction Stop

    return 0
}
catch
{
    return 99
}
</code></pre>

<p>This is how I'm calling the script from my python script:</p>

<pre><code>req =    subprocess.Popen([r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
                             '-ExecutionPolicy',
                             'Unrestricted',
                             './call.ps1',
                             param1, param2], cwd=os.getcwd())

    print("^^^^^^^")
    result = req.wait() #something is going wrong here
    print("****************")
    print(result)

    if result == 0:
        # do something
    else:
        # do something else
</code></pre>

<p>Now this is where its going wrong... even when the POST request is failing the "result" variable still has "0" and not "99". When I separately run the powershell script I can see that its returning 99 when the POST request is failing. So the problem is not with the powershell file it seems.</p>

<p>On debugging python file, this is what i see on console: (notice the order of print statements in the python code)</p>

<pre><code>^^^^^^^
99
****************
0
</code></pre>

<p>One thing that I don't understand is.. what is "99" doing in the output? I'm not even printing the result between "^^^^^" and "*****". So if the powershell script is returning 99, why does it change to 0 after "*****".</p>

<p>I'm really lost here. Please help.</p>

<p>req.wait() will return the exit code of the program you ran. In this case, power shell returns a good exit code of 0. It seems to just print out "99", which is what you are seeing in the output.</p>

<p>You may want to use: </p>

<pre><code>out = subprocess.check_output(...)
print out
</code></pre>

python powershell popen