Jane Dilbert
Jane Dilbert

Reputation: 13

Python running in Windows subprocess.call with spaces and parameters

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

Answers (2)

tripleee
tripleee

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

wuerfelfreak
wuerfelfreak

Reputation: 2439

You can escape the spaces by

  • By enclosing the path (or parts of it) in double quotation marks ( ” ).
  • By adding a caret character ( ^ ) before each space. (This only works in Command Prompt/CMD, and it doesn’t seem to work with every command.)
  • By adding a grave accent character ( ` ) before each space. (This only works in PowerShell, but it always works.)

Source

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

Related Questions