Reputation: 13
I'm trying to create a script replacing PowerShell that looks for certain files and passes arguments to another process.
I can call the subprocess if is in the same folder. And I can pass one parameter or one file name. But I am not able to call the subprocess if the exe path has spaces. And I am not able to pass the file name and parameters together.
import os
import subprocess
cmd = "C:\\Program Files\\Some Installed App\\App.exe"
params = "--param1 val1 --param2 val2 --param3 val3 --param4 val4"
for file in os.scandir():
if file.path.endswith("SomeExt"):
subprocess.call([
cmd,
os.path.abspath(file.path), params
], shell=True)
How can I pass these parameters successfully and use the path with spaces? Is usually located in Program Files and I can't change that.
Upvotes: 0
Views: 2036
Reputation: 189397
If you pass in a list, every parameter needs to be a separate list element.
If you are lazy, or need to accept a string containing the parameters from an outside source, you can use shlex.split()
to split a string into separate strings, with (Unix) shell quoting semantics. For example,
--param "parameter one"
gets split into the list
['--param', 'parameter one']
But in your case, with a hard-coded list, just split it yourself.
cmd = "C:\\Program Files\\Some Installed App\\App.exe"
params = ["--param1", "val1", "--param2", "val2", "--param3", "val3", "--param4", "val4"]
for file in os.scandir():
if file.path.endswith("SomeExt"):
subprocess.call([cmd] +
[os.path.abspath(file.path)] +
params)
Upvotes: 2
Reputation: 2439
You can escape the spaces by
cmd = "C:\\\"Program Files\"\\\"Some Installed App\"\\App.exe"
cmd = "C:\\Program^ Files\\Some^ Installed^ App\\App.exe"
cmd = "C:\\Program` Files\\Some` Installed` App\\App.exe"
Upvotes: 1