Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I used 2 quotes in os.system? PYTHON

Tags:

python

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?

like image 340
Jon smith Avatar asked Dec 02 '22 23:12

Jon smith


1 Answers

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.

like image 149
David Heffernan Avatar answered Dec 09 '22 15:12

David Heffernan