2

I am trying to execute a windows executable which could be located in "c:\program files\folder" using python. The get_me_the_path() routine returns the exe path located in "c:\program files\folder". I tried various things like replacing "\" with "\\" and " " with "\ " OR even changing "\" to "/" BUT everytime I get the same error

Issue is that i want to convert output_path variable to some form which subprocess.check_output can execute without issues. Few people suggested normpath but that too doesn't help and I get the same error.

try:
    output_path= os.path.join(get_me_the_path()) ;
    exepath = output_path.replace("\\", "/").replace(" ", "\\ ")
    subprocess.check_output(exepath,shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

This is the error I am getting every time

RuntimeError: command 'C:/Program\ Files/folder/mytool.exe' return with error (code 1):
  b"'C:/Program\\' is not recognized as an internal or external command, operable program
    or batch file.
martineau
  • 119,623
  • 25
  • 170
  • 301
Helena
  • 444
  • 2
  • 15
  • Have you tried `[exepath]`? – Thomas Weller Feb 10 '22 at 11:15
  • 1
    Try enclosing the string `get_me_the_path()` returns in double quote `"` characters so it's literally `"c:\program files\folder"`. i.e. `exepath = f'"{get_me_the_path()}"'` – martineau Feb 10 '22 at 11:16
  • @ThomasWeller : Did you mean `subprocess.check_output([exepath],shell=True,stderr=subprocess.STDOUT)` – Helena Feb 10 '22 at 11:16
  • 2
    Why did you even use `shell=True`? Now you're dealing with the nastiness of manual Windows command escaping. – user2357112 Feb 10 '22 at 11:17
  • Yes, that way the parser knows that the first item in the list is the executable and the others are arguments (no arguments in your case, thus the array only contains the executable) – Thomas Weller Feb 10 '22 at 11:18
  • @user2357112 supports Monica : What is your suggestion. I am trying to run an exe and don't know correct way. – Helena Feb 10 '22 at 11:20
  • @ThomasWeller : with [exepath], it has stopped working altogether. Just throws exception – Helena Feb 10 '22 at 11:22
  • @user2357112supportsMonica says that `shell=True` is problematic and you might want to try `shell=False` if you don't need the shell functionality. – Thomas Weller Feb 10 '22 at 11:27
  • @ThomasWeller : What should be the syntax if the exe has any arguments? – Helena Feb 10 '22 at 11:31
  • `[exepath, arg1, arg2]` – Thomas Weller Feb 10 '22 at 11:38
  • Possible duplicate of [Actual meaning of `shell=True` in subprocess](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess) – tripleee Feb 10 '22 at 13:11

0 Answers0