Python subprocess – attempting to use a powershell script, but whitespaces in filepath cause errors

Question:

Background: Trying to monitor something in Windows which is trivial to do in Powershell but a massive pain in Python. I would like to call a Powershell script from Python, have it print ‘True’ or ‘False’ to stdout, capture said output in Python, and continue on with the Python program.

The Problem: There are whitespaces in the path to the Powershell file. I have googled and tried every combination of double quotes, single quotes, backslashes and front slashes I can think of, but Powershell keeps throwing an error when the string is passed to it.

What does work: If I start the program from a location where I can run it with a whitespace-free relative path, everything works fine:

result = subprocess.run(['powershell', "PythonCheckProcessprocessCheck.ps1", "processName"], stdout=subprocess.PIPE)

Examples of what does not work:

Trying the following:

result = subprocess.run(['powershell', "C:\Path with spaces\Python\CheckProcess\processCheck.ps1", "processName"], stdout=subprocess.PIPE)

result = subprocess.run(['powershell', r"C:Path with spacesPythonCheckProcessprocessCheck.ps1", "processName"], stdout=subprocess.PIPE)

result = subprocess.run(['powershell', "C:Path with spacesPythonCheckProcessprocessCheck.ps1", "processName"], stdout=subprocess.PIPE)

results in variations of: "The term ‘C:\Path’ is not recognized as the name of a cmdlet, function, script file, or noperable program"

Trying the following:

result = subprocess.run(['powershell', "C:Path with spacesPythonCheckProcessprocessCheck.ps1", "processName"], stdout=subprocess.PIPE)

Results in: "SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes"

And finally the following:

result = subprocess.run(['powershell', "'C:\Path with spaces\Python\CheckProcess\processCheck.ps1'", "processName"], stdout=subprocess.PIPE)

result = subprocess.run(['powershell', '"C:\Path with spaces\Python\CheckProcess\processCheck.ps1"', "processName"], stdout=subprocess.PIPE)

result = subprocess.run(['powershell', '"""C:\Path with spaces\Python\CheckProcess\processCheck.ps1"""', "processName"], stdout=subprocess.PIPE)

Return the message: Unexpected token ‘processName’ in expression or statement

Powershell or Python?

At least part of the problem seems to be that Python likes to create strings with doubled up backslashes (e.g. "C:\Some Folder\Another Folder") and Powershell cannot handle that in a filepath. I’ve experimented with the Pathlib module, but it just creates strings similar to the ones above resulting in the same error messages. Really stumped on how to get these languages to play well together.

Asked By: TripleD

||

Answers:

Put "r" before the string with the filename. And you can use just one "".

r"C:Path with spacesPythonCheckProcessprocessCheck.ps1"
Answered By: LetzerWille