Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute powershell script from python with space in the path and parameters

Path example: C:\Users\user\Some Space\dev\sensor\

def readSensorList():
    with open('sensor.json') as json_data:
        data = json.load(json_data)
    json_data.close()

return data
def executeSensor():
    sensorList = list()
    sensorListRaw = readSensorList()
    for sensor in sensorListRaw['sensors']:
        x = [subprocess.Popen(['powershell.exe','-ExecutionPolicy', 'Unrestricted', sensorListRaw["path"] + sensor["filename"], "-name", sensor["name"]], stdout=subprocess.PIPE, stderr=subprocess.PIPE), sensor["name"]]
        sensorList.append(x)
    return sensorList

Json containing the path:

{
                "path": "C:\\Users\\\\sensor\\",
                "sensors": 
                    [{
                        "name": "partition",
                        "filename": "partition.ps1"
                    }]
            }

In my test environnement there were no space in the path, but now, in the production, I have some space in the path, and I'm clueless about how to execute powershell script from python with space and parameters

I tried to quote the path, without any success.

Edit: I'm sure the problem come from the powershell.exe command and not from python, because:

powershell.exe -ExecutionPolicy 'Unrestricted C:\Users\some space\Desktop\PythonSensor\sensor\sensor.ps1'

Don't work in the CMD.

like image 686
MacTheZazou Avatar asked Jan 06 '23 23:01

MacTheZazou


1 Answers

I finally found, you have to put ' between space like this:

powershell -command "C:\Users\me\Desktop\test\ps' 'test.ps1"

In python:

subprocess.Popen(['powershell','-ExecutionPolicy', 'Unrestricted', '-command', path]

with path as:

C:\Users\me\Desktop\some' 'space\sensor\ 

without " as Serge Ballesta explain.

like image 86
MacTheZazou Avatar answered Feb 01 '23 22:02

MacTheZazou