5

I have a little bit of problem when I'm trying to use 2 quotes in os.system.. I'm gonna launch a program with python, the directory has multiple spaces, and to launch something that has multiple spaces in CMD you need to put double quotes around it obviously.

And here comes the thingy.. my code looks like this:

import os
os.system("C:/t est/hello")

and since I used os.system, it will obviously just send C:/t est/hello that to CMD..

Now what I need is to send "C:/t est/hello" to cmd with quotes but I need python to understand that I need 2 quotes aswell. Can someone please help me?

glglgl
  • 89,107
  • 13
  • 149
  • 217
Jon smith
  • 53
  • 1
  • 1
  • 4
  • Seems like you just need escape characters print "Hello \"world\"" outputs 'Hello "World"' – David Apr 23 '13 at 18:58
  • @summea No, I need os.system to send "C:/t est/hello" to CMD, instead of just sending C:/t est/hello without double quotes because without the quotes CMD will just go to c:/t because there is a space in it. – Jon smith Apr 23 '13 at 19:00
  • Or use single quotes and include double quotes inside the string like this: `os.system('"C:\\t est\\hello"')` or specify the string to be processed as it comes with an *r* before the single quotes like this: `os.system(r'"C:\t est\hello"')` – Paulo Bu Apr 23 '13 at 19:05

1 Answers1

20

If you want to add quotes to your command, simply do so. Possibly the easiest way is to use single quotes for your string:

os.system('"C:/t est/hello"')

If you want to write a double quote inside a string delimited by double quotes you need to escape it. That would be done like this:

os.system("\"C:/t est/hello\"")

However, it's just a lot easier to use subprocess instead and let it handle quoting for you. For example:

subprocess.check_call(['ls', 'some directory with spaces in'])

Even the documentation for os.system() recommends using subprocess:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Gives an error to :/, it kind of needs to be like this somehow like this i think ""DIRECTORY HERE"" – Jon smith Apr 23 '13 at 19:07
  • 1
    Not only does `subprocess` work, it is superbly designed. I've just finished a large development project where we moved all our build scripts to Python. All run on top of `subprocess`. It would have been a nightmare with `os.system()`. It was trivially easy with `subprocess`. I cannot praise it highly enough. – David Heffernan Apr 23 '13 at 19:14
  • That's what it was made for. Dunno why people still are messing around with `os.system()`... – glglgl Apr 23 '13 at 20:39
  • Wow, thank you for subprocess tip - helped a lot) – Maryna Klokova Sep 28 '21 at 20:16