0

I've found that python can run other programs using the subprocess module. I want to use python to run a powershell script that is in a directory location that contains spaces. How do I handle the spaces in the python script below?

import subprocess
powershellExeLocation = r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
powershellScriptLocation = r"C:\Users\username\Documents\testPowershell.ps1"
print('running script with no spaces')
#this works
subprocess.run([powershellExeLocation, powershellScriptLocation])
#this doesn't work
print('running script with spaces')
powershellScriptLocationWithSpaces = r"C:\Users\username\path with spaces\testPowershell.ps1"
subprocess.run([powershellExeLocation, powershellScriptLocationWithSpaces])

2 Answers 2

1

Try this:

subprocess.run([powershellExeLocation, "-File", powershellScriptLocationWithSpaces])
Sign up to request clarification or add additional context in comments.

Comments

0

The script location needs a set of literal quotes around it, so powershell.exe knows to treat it as one single filename.

subprocess.run([powershellExeLocation, '"' + powershellScriptLocationWithSpaces + '"'])

2 Comments

This doesn't work for me. I added quotes as shown to paths with and without spaces and it broke the ability to run the script in both cases.
There is no error produced, but it behaves as if the path to the powershell script was not found - the powershell window opens and closes immediately, rather than running the script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.