2
votes

When I launch a PowerShell script from Python, the delay seems to be approximately 45s, and I cannot figure out why.

I'm trying to run a PowerShell script (accessing some APIs only available to PowerShell) from a Python script.

I've tried a lot of permutations, and all incur ~45 second delay compared to just running the script from a command prompt, using an identical command line.

For example - sample.ps1 might say:

echo foo

And runner.py might say:

import subprocess
p = subprocess.Popen([POWERSHELL, '-File', 'sample.ps1'], stdout=subprocess.STDOUT)
d = p.stdout.read()

Running the .ps1 script directly is fast, running it via runner.py (Python 2.7, 32bit on a 64bit machine) incurs 45 second delay.

The exact same thing occurs if I use "os.system", or Twisted's built-in process tools. So I suspect it's some subtle interaction between the Python interpreter and the Powershell interpreter, possibly related to creation of console windows, or handling of stdin/out/err streams? (which I know don't "really exist" in the same way on Windows)

2
Is there any chance you have a profile loading that is delaying startup? - Greg Wojan
No. There is no profile loading. - Realist

2 Answers

0
votes

I do not see any such delays. It is pretty snappy. ( that will also depend on what your script actually does.) Try using call:

from subprocess import call
call(["powershell", "sample.ps1"])
0
votes

PowerShell loads your user's profile by default. Use the -NoProfile argument to turn that behavior off:

import subprocess
p = subprocess.Popen([POWERSHELL, '-NoProfile', '-File', 'sample.ps1'], stdout=subprocess.STDOUT)
d = p.stdout.read()