Feign
Feign

Reputation: 270

How to escape special characters and run a command in command prompt?

I have a two part question. First, I have a string that looks like this

C:\Users\me\Desktop\Personal\Songs\U2 - Beautiful Day.mp3

Now, I'd like to open this file from my program using something like

os.system("start "+that_string)

Sadly, I get an error in command prompt because it tries to open the file

C:\Users\me\Desktop\Personal\Songs\U2

This is due to the spaces in my string. This means I need to use quotation marks around the whole string... like this in cmd

start "C:\Users\me\Desktop\Personal\Songs\U2 - Beautiful Day.mp3"

so the first part to my question is, how do add those quotation marks to my string?

Next, when I actually do run that last command in command prompt, all it does is open another instance of command prompt. So, am I using the wrong command to open a file in its default program? If so, which command should I be using?

Upvotes: 1

Views: 1261

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 178409

Try this:

os.startfile(r'C:\Users\me\Desktop\Personal\Songs\U2 - Beautiful Day.mp3')

It's like double-clicking the file in explorer and runs the default program for the file's extension. Also noted the r at the start of the string. That is a "raw" string and the backslashes won't be processed as escape codes.

But to answer your question, Python can use both single- and double-quotes to make strings, so if you want embedded double-quotes you can use single-quotes to quote the string.

os.system('start "'+that_string+'"')

Upvotes: 1

Related Questions