gpt4 book ai didi

python - 如何使用路径和参数中的空格从python执行powershell脚本

转载 作者:行者123 更新时间:2023-11-28 20:39:39 24 4
gpt4 key购买 nike

路径示例: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:

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

在我的测试环境中,路径中没有空格,但现在,在生产环境中,路径中有一些空格,我对如何使用空格和参数从 python 执行 powershell 脚本一无所知

我尝试引用路径,但没有成功。

编辑:我确定问题出在 powershell.exe 命令而不是 python,因为:

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

不要在 CMD 中工作。

最佳答案

我终于发现,你必须像这样把'放在空格之间:

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

在 python 中:

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

路径为:

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

如 Serge Ballesta 所解释的,没有 "。

关于python - 如何使用路径和参数中的空格从python执行powershell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37547587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com