0

How can I run a command that requires a filepath that contains spaces when using the start command with os.system

For Example:

# path_d[key] = C:\Users\John\Documents\Some File With Space.exe
path = path_d[key]
os.system("start {0}".format(path))

When I try running it I end up getting an error saying:

Windows cannot find 'C:\Users\John\Documents\Some.'. Make sure you typed the name correctly, and then try again.
1

2 Answers 2

1

i do the following

path = path_d[key]
os.system(r'start "{0}"'.format(path))

so, surround the path with double quotes. that way it will take care of spaces in path. if there is no default application to open, it might open command prompt. So, if its a text file do the following

os.system(r'notepad "{0}"'.format(path))
Sign up to request clarification or add additional context in comments.

8 Comments

I tried this and it seemed to result in opening a command prompt with the title as the path name
if its an exe, you directly give path to the exe instead of putting start infornt of it
I found that os.system(r'start "random title" "{0}"'.format(path)) worked well. MS-DOS 'start' command expects a title for the first argument if you use quotations.
@Sam, looks like its already answered at stackoverflow.com/questions/6977215/…
It seems the question you linked doesn't include the use of "start" call. I've edited my question to reflect that.
|
1

You need to properly escape your special characters in path, which might be easily done as such:

path = r"C:\Users\John\Documents\Some File With Space.exe"

To execute it under Windows:

import os

os.system(r"C:\Users\John\Documents\Some File With Space.exe")

EDIT

per request of OP:

path_dict = {"path1": r"C:\Users\John\Documents\Some File With Space.exe"}
os.system('{}'.format(path_dict["path1"]))

2 Comments

How could I make it if the filepath is stored as a dictionary and not hardcoded?
@InAFlash I added (edited) the post including the way I execute it and it works fine under python2 on my machine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.