3

This is probably a really simple issue, but I am having the hardest time with it. I'm trying to execute a command prompt command in Python, but since I have spaces in the path (C:\Program Files\etc) it says that "C:\Program" is not a recognized command

So far I have tried to use the escape character backslash \ to interpret the spaces as actual spaces, but this didn't work. I also tried doing ('"'+chkcmd+'"') but that didnt work either. Here is the simple code I'm trying to use:

chkcmd = "C:\Program Files\whatever.exe"
os.system(chkcmd)

Any help would be greatly appreciated. Thank you!

Alan
  • 265
  • 1
  • 3
  • 15
  • 1
    Possible duplicate of [escape whitespaces in linux path and file names](http://stackoverflow.com/questions/24844707/escape-whitespaces-in-linux-path-and-file-names) – Chris_Rands Nov 16 '16 at 14:37
  • 1
    http://stackoverflow.com/questions/6977215/os-system-to-invoke-an-exe-which-lies-in-a-dir-whose-name-contains-whitespace – Danny Cullen Nov 16 '16 at 14:37
  • To me `os.system('"'+chkcmd+'"')` seem to work (it complains about `C:\Program Files\whatever.exe` doesn't exist, but that's expected as I don't have that executable here). – skyking Nov 16 '16 at 14:38
  • Also note that you shouldn't use single backslash in a string literal to make a backslash - you should use double backslash in order to distinguish it from backslashes used to escape special characters (eg '\n`). – skyking Nov 16 '16 at 14:52
  • Possible duplicate of [How do I execute a program from python? os.system fails due to spaces in path](http://stackoverflow.com/questions/204017/how-do-i-execute-a-program-from-python-os-system-fails-due-to-spaces-in-path) – kabanus Nov 16 '16 at 14:57
  • 1
    I tried both the double backslashes and what skyking mentioned, but neither of them worked. Are there any other ways to make it recognize that there are spaces in the path? – Alan Nov 16 '16 at 15:06
  • when you write a windows path use [raw string](https://docs.python.org/3.4/library/stdtypes.html?highlight=raw#text-sequence-type-str), that way you don need to worry about escapes special characters character. To use it you only nee to append a `r` add the start of the string. For example `r"c:\notepad.exe"`. Now compare both with and without the `r` by printing them – Copperfield Nov 16 '16 at 15:18
  • 1
    @Copperfield, so that works... kind of. In this command prompt command, I need to have double quotes after a pipe. So the final command will look like `c:\program files\whatever.exe -version | find "example"` But it is ending the double quotes right before example. So it never gets to the word `example` – Alan Nov 16 '16 at 15:32
  • try with `"c:\program files\whatever.exe" -version | find "example"` or `'"c:\program files\whatever.exe" -version | find "example"'` (notice the that is a string build with `'` ) – Copperfield Nov 16 '16 at 20:58

0 Answers0